【问题标题】:Add onclick Event to a jQuery.each()将 onclick 事件添加到 jQuery.each()
【发布时间】:2017-09-27 09:44:51
【问题描述】:

我是 Javascript 和 jQuery 的新手。这是我的 JSON 文件。我想向 jQuery.each() 添加一个 jQuery onclick 事件。这是我的代码。

{
  "1": [{
    "RequestId": "1",
    "CustomerId": "1",
    "RequestCharge": "100.00",
    "Trade": ""

  }],
  "2": [{
    "RequestId": "1",
    "CustomerId": "1",
    "RequestCharge": "100.00",
    "Trade": ""
  }],
  "3": [{
    "RequestId": "1",
    "CustomerId": "1",
    "RequestCharge": "50.00",
    "Trade": ""
  }]
}

下面的代码运行良好

 $.each(output, function(i) {                   
    var tr = $('<tr/>');
    tr.append("<td>" + output[i][0].RequestId + "-"  +"</td>");
    tr.append("<td>" + output[i][0].CustomerId + "-" + "</td>");
    tr.append("<td>" + output[i][0].RequestCharge + "</td>");
    $("#whad").append(tr);
    });

但我想添加一个点击功能,每个给定的 i 值。 这是我下面的代码,但我未定义。

$.each(output, function(i) {                    
        var tr = $('<tr/>');
        tr.append("<td>" + output[i][0].RequestId + "-"  +"</td>");
        tr.append("<td>" + output[i][0].CustomerId + "-" + "</td>");
        tr.append("<td>" + output[i][0].RequestCharge + "</td>");
        $("#whad").append(tr).click(function() {
            console.log("This is the value of i clicked: " + this.i)
        });
        });

这是我的html。

    <table id = "whad"> </table>

我需要 this.i 来返回点击的值。

【问题讨论】:

标签: javascript jquery json


【解决方案1】:

你可以将json解析成一个对象:

var obj = JSON.parse(text);

然后从对象中检索值:

obj["1"][0].RequestId

如果你想全部显示,你需要遍历数组并打印你想要的值:

for (var i = 0; i<output.length; i++) {
    $("#YOURDIV").append("Request id: " + obj[i][0].RequestId);
    $("#YOURDIV").append("Customer id: " + obj[i][0].CustomerId);
    $("#YOURDIV").append("Request Charge : " + obj[i][0].RequestCharge);
}

【讨论】:

  • 成功了。显示第一个 RequestId。但是如何在 JSON 文件中显示所有 RequestId?
  • 只需循环遍历数组中的所有元素 :)
  • 我已经编辑了我的问题。知道为什么代码不起作用吗?
  • 您编辑的代码不起作用。我的 3 个 div 是空白的。
猜你喜欢
  • 2012-06-16
  • 1970-01-01
  • 2012-06-09
  • 2012-10-08
  • 2013-05-04
  • 2021-10-26
  • 1970-01-01
  • 1970-01-01
  • 2011-10-20
相关资源
最近更新 更多