簡體   English   中英

在javascript中創建按鈕並設置其值

[英]Creating button and setting its value in javascript

 $(document).ready(function() { $("#getDevicesButton").click(getContactList); //$("#getDeviceResourcesButton").click(getDeviceResources); }); function onDeviceReady() { getContactList(); getDeviceResources(); } function getDeviceResources(value) { alert("getDeviceResources clicked, value passed " + value); } function getContactList() { $.ajax({ url: "https://api.connector.mbed.com/endpoints/", dataType: "json", type: "GET", headers: { "Authorization": "Bearer <removed>" }, cache: false, error: function(xhr, ajaxOptions, thrownError) { debugger; alert(xhr.statusText); alert(thrownError); }, success: function(json) { for (var i in json) { $('#deviceList').append('Device #' + (i) + ': <br/> name: ' + json[i].name + '<br/> type: ' + json[i].type + '<br/> <button id=getDeviceResourcesButton onclick=getDeviceResources(' + i + ')>Get Device Resources</button>'); } } }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <h3>Device List</h3> <button id="getDevicesButton">Get Devices</button> <ul id="deviceList"></ul> </body> 

在javascript函數內部,我有一個稱為json的JSON結果。 我像這樣遍歷它:

for (var i in json)
{
    $('#deviceList').append('Device #' +(i)+ ': <br/> name: ' + json[i].name + '<br/> type: ' + json[i].type + '<br/> <button id=getDeviceResourcesButton onclick=getDeviceResources('+i+')>Get Device Resources</button>');
}

當前getDeviceResources定義為

function getDeviceResources(value)
{
    alert("getDeviceResources clicked, value passed "+value);
}

我的問題-就這樣,我得到了帶有預期值的警報,但是如果我將+i+更改為+json[i].name+我什至沒有警報。

知道我想念什么嗎?

謝謝,

您沒有將json[i].name作為字符串傳遞給該函數。 i情況下,它不會拋出錯誤,因為它是整數。 是一個證明相同的小提琴。

function getDeviceResources(value)
{
    alert("getDeviceResources clicked, value passed "+value);
}
json = [
{name: "abc"},
{name: "bcd"}
];
console.log(json);
$(function(){
for (var i in json)
{
  $('#deviceList').append('Device #' +(i)+ ': <br/> name: ' + json[i].name + '<br/> type: ' + json[i].type + '<br/> <button id=getDeviceResourcesButton onclick=getDeviceResources("'+json[i].name+'")>Get Device Resources</button>');
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM