2016-03-31 24 views
0

創建按鈕並設置其值在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+我什至不知道警報。

任何想法我錯過了什麼?

感謝,

+0

「有什麼想法我錯過了什麼?」 - 一條錯誤消息,可能是在警報顯示之前放棄您的代碼。檢查你的控制檯。 – Amadan

+0

(1)不要使用'alert'進行調試,使用'console.log'和JavaScript調試器。有關詳情,請參閱這些[Chrome DevTools提示](https://developers.google.com/web/tools/chrome-devtools/?hl=zh-CN)。其他瀏覽器也有類似的開發者工具。 (2)沒有人可以從代碼摘錄中知道什麼是錯的。發佈一個完整的可運行示例,可以作爲[Stack Overflow code snippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/)或[小提琴](https://jsfiddle.net/)。 –

+0

感謝您的意見,增加了代碼。 – ranshe

回答

0

你是不是傳遞json[i].name作爲一個字符串的函數。在i的情況下,它不會拋出一個錯誤,因爲它是一個整數。 Here是一個演示相同的小提琴。

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>'); 
    } 
}); 
+0

我知道它必須是這樣的東西..謝謝! – ranshe