我有一个对象,其中存储了数据。我有它,用户可以选择一个选项,然后出现结果列表。结果是链接。单击链接后,我希望有关公司的数据显示为表格。唯一的事情是,我不知道如何在单击链接时将其放置在何处,JavaScript会从该链接中获取数据并将其放入将显示的html表中。我的问题是如何将html元素链接到对象中的数据,然后允许该数据显示在表中?无需更改我原始代码的方向。
$("#listingResults").html("Business Listings Under Category <strong>" + textNameOfBusinessSelected + "</strong> are: <br/><br/><ul id='listOfBusinesses'><li><a href='javascript-exercise-16.html#bottomOfPage' onclick='clickListingLink()'>" + businessListNames.join("<br/><a href='javascript-exercise-16.html#bottomOfPage' onclick='clickListingLink()'><li>") + "</li></ul>");
} // line closes function
function clickListingLink() {
// function is for when a link is clicked after list of businesses appear
$('#listOfBusinesses').on('click','li', function(){
clickListingLink();
console.log('you clicked me');
seeListingInfoTable();
$("hr").show();
});
}
function seeListingInfoTable(titleOfBusinessSelected, businessLinkSelected) {
// function is for table that shows info of specific link clicked
console.log("apple");
var tbl = "";
tbl += '<table class="table table-hover">';
tbl += '</table>';
tbl += '<tbody>';
tbl += '<caption class="listingTitle">' + titleOfBusinessSelected + '</caption>';
tbl += '<tr>';
tbl += '<th>Address</th>';
tbl += '<th>Phone Number</th>';
tbl += '<th>Website</th>';
tbl += '<th>Specialty</th>';
tbl += '</tr>';
tbl += '<tr>';
tbl += '<td><div class="row_data" edit_type="click" col_name="fname">' + businessLinkSelected["Address"] + '</div></td>';
tbl += '<td><div class="row_data" edit_type="click" col_name="fname">' + businessLinkSelected["Phone Number"] + '</div></td>';
tbl += '<td><div class="row_data" edit_type="click" col_name="fname">' + businessLinkSelected["Website"] + '</div></td>';
tbl += '<td><div class="row_data" edit_type="click" col_name="fname">' + businessLinkSelected["Specialty"] + '</div></td>';
tbl += '</tr>';
tbl += '</tbody>';
tbl += '</table>';
$(document).find("#infoTable").html(tbl);
} // line ends seeListingInfoTable function
答案 0 :(得分:0)
最简单的方法是将data attributes添加到您的HTML中,例如<a href="#" data-name=" + businessName + " data-address=" + businessAddress +">
,然后使用jQuery .data() method来获取它们。
我创建了一个显示逻辑的最小示例,因此您可以在代码中实现它。
var $person = $('.person');
var $resultName = $('.result-name');
var $resultAge = $('.result-age');
$person.on('click', function() {
var $this = $(this);
var name = $this.data('name');
var age = $this.data('age');
$resultName.html(name);
$resultAge.html(age);
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<ul>
<li><a class="person" href="#" data-name="John Doe" data-age="12">One</a></li>
<li><a class="person" href="#" data-name="Mark Z" data-age="23">Two</a></li>
</ul>
<div class="result">
<p>Name: <span class="result-name"></span></p>
<p>Age: <span class="result-age"></p>
</div>