2017-09-27 74 views
-6

我是JavaScript和jQuery的新手。這是我的JSON文件。我想爲jQuery.each()添加一個jQuery onclick事件。這是我的代碼。添加onclick事件到jQuery.each()

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

但我想添加點擊功能與我的每一個給予的價值。 這是我的代碼在下面,但我沒有定義。

$.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返回一個點擊的值。

+0

你想提取什麼? –

+2

請花些時間閱讀幫助頁面,尤其是名爲[「我可以詢問什麼主題?」(http://stackoverflow.com/help/on-topic)和[「應該提供哪些類型的問題我避免問?「](http://stackoverflow.com/help/dont-ask)。更重要的是,請閱讀[Stack Overflow問題清單](http://meta.stackexchange.com/q/156810/204922)。您可能還想了解[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 –

+0

RequestId,CustomerId和RequestCharge – 1plus

回答

0

您可以解析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); 
} 
+0

它工作。顯示第一個RequestId。但是,我如何顯示JSON文件中的所有RequestId? – 1plus

+0

只是遍歷數組中的所有元素:) –

+0

我編輯了我的問題。任何想法爲什麼代碼不工作? – 1plus