首页 > 解决方案 > 使用 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"
        }
    ]
 }

标签: javascriptjqueryjson

解决方案


您可以将单击事件处理程序绑定到您创建的行,该行可以获取该行的链接并将其用于浏览器位置以重定向到链接位置。

$(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");
    });
  });
});

推荐阅读