我将作为JSON数据的新项目添加到表中。我有一个名称,价格,类别和链接。如何做到这一点,以便在单击特定行时可以访问与该项目关联的链接?
HTML
<main>
<table id= "userdata" >
<thead>
<th>title</th>
<th>category</th>
<th>price</th>
</thead>
</table>
</main>
JavaScript
$(function() {
$.getJSON('catalog.json', function(data) {
$.each(data.catalog, function(i, f) {
const tblRow = "<tr>" + f.link + "<td>" + f.title + "</td>" + "<td>" + f.category + "</td>" + "<td>" + f.price + "</td>" + "</tr>";
$(tblRow).appendTo("#userdata ");
});
});
$(document).on('click', 'tr', function(){
console.log(this.link);
});
});
项目数据
{
"catalog": [
{
"title": "ФТ-45",
"category": "Шкаф",
"price": 200,
"link":"/1.html"
},
{
"title": "Наташа",
"category": "Диван",
"price": 300,
"link":"/2.html"
},
{
"title": "Peter",
"category": "Шкаф",
"price": 400,
"link":"/3.html"
},
{
"title": "Сокол",
"category": "Кресло",
"price": 400,
"link":"/4.html"
}
]
}
答案 0 :(得分:1)
您可以将click事件处理程序绑定到您创建的行,该行可以获取该行的链接,并将其用于浏览器位置以重定向到链接位置。
$(function() {
$.getJSON('catalog.json', function(data) {
$.each(data.catalog, function(i, category) {
let $tblRow = $(
"<tr><td>"+ category.title +
"</td><td>"+ category.category +
"</td><td>"+ category.price +
"</td></tr>"
);
$tblRow.on('click', function(e){
window.location = category.link;
});
$tblRow.appendTo("#userdata");
});
});
});
答案 1 :(得分:-1)
向行元素添加自定义数据值。
$(tblRow).data("item-index", i)
然后您可以使用
获得该值var index = $(this).data("item-index");
console.log(data[index]);