javascript - 使用 json 链接到字符串
问题描述
我将新项目添加到以 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"
}
]
}
解决方案
您可以将单击事件处理程序绑定到您创建的行,该行可以获取该行的链接并将其用于浏览器位置以重定向到链接位置。
$(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");
});
});
});
推荐阅读
- html - 如何使用模糊滤镜使图片作为背景
- sql - 我的表包含 tdate 列,数据类型 date
- typescript - TypeScript 中的原子类型区分(标称原子类型)
- visual-studio-code - 通过 vscode API 访问硬件/设备信息
- spring - 我们可以在spring中使用没有@repository注解的DAO吗
- javascript - 如何使用函数式编程范式转换 jquery grep 函数?
- xquery - 有没有办法按输入中的位置范围对记录进行分组?
- python-3.x - Python 控制台中是否有重置功能?
- ionic4 - 使图像适合离子卡
- python-3.x - HTTP 与 TCP 保持活动状态?