2016-04-21 96 views
0

我有一個從數據庫獲取值並返回json對象的wcf服務。我試圖創建輸入按鈕取決於返回值:在JavaScript中創建類型按鈕的輸入

$.ajax({ 
    type: "POST", 
    contentType: "application/json; charset=utf-8", 
    url: "My Servic URL", 
    processData: false, 
    dataType: "json", 
    success: function(response) { 
    var foo = document.getElementById("hmengcont"); 
    foo.innerHTML = ""; 
    for (var i = 0; i < eval(response.d).length; i++) { 
     var element = document.createElement("input"); 
     //Assign different attributes to the element. 
     element.type = "button"; 
     element.id = eval(response.d)[i].CityID; 
     element.class = "show-page-loading-msg"; 
     element.style = "width: 100%;height: 50px; border-radius: 5px;-webkit-appearance: inherit;cursor: pointer; opacity: 5.1;z-index: 2;color: #131212;background: rgba(255, 255, 255, 0);"; 
     element.value = eval(response.d)[i].CityNameEng; // Really? You want the default value to be the type string? 
     element.name = eval(response.d)[i].CityID; 
     element.onclick = function() { // Note this is a function 
     alert(element.value); 
     } 
     ");"; 
     foo.appendChild(element); 
    } 
    }, 
    error: function(a, b, c) { 
    alert(a.responseText); 
    } 
}); 

成功創建按鈕和所有的人都有自己的正確的價值觀,但在點擊警報僅返回最新的值。

+0

1)在click處理程序中使用'this'關鍵字來引用被點擊的按鈕:'console.log(this.value)'。 2)你應該使用jQuery創建元素 - 你可以將'for'循環中的代碼縮短爲幾行3)在元素上使用CSS類而不是內聯樣式4)*不使用eval * - 它是可怕的做法,當你多次使用它來解碼同一個對象時會變得更糟。 5)使用單個委託事件處理程序來處理您添加的所有按鈕的點擊 –

回答

0

在您的警報,而不是element.value改變它this.value。像下面這樣,

element.onclick = function() { // Note this is a function 
    alert(this.value); 
} 
0
$.ajax({ 
    type: "POST", 
    contentType: "application/json; charset=utf-8", 
    url: "My Servic URL", 
    processData: false, 
    dataType: "json", 
    success: function (response) { 
     var foo = document.getElementById("hmengcont"); 
     foo.innerHTML = ""; 
     for (var i = 0; i < eval(response.d).length; i++) 
     { 
      $("<input>", { 
       type: "button", 
       id: eval(response.d)[i].CityID, 
       class: "show-page-loading-msg", 
       style: "width: 100%;height: 50px; border-radius: 5px;-webkit-appearance: inherit;cursor: pointer; opacity: 5.1;z-index: 2;color: #131212;background: rgba(255, 255, 255, 0);", 
       value: eval(response.d)[i].CityNameEng, // Really? You want the default value to be the type string? 
       name: eval(response.d)[i].CityID 
      }).appendTo($("#hmengcont")); 
     } 
    }, 
    error: function (a, b, c) { 
     alert(a.responseText); 
    } 
}); 
$(document).on("click", "button.show-page-loading-msg", function() { 
    var arrButtons = $("button.show-page-loading-msg"); 
    $.each(arrButtons, function() { 
     alert($(this).val()); 
    }); 
}) 
相關問題