我有一个从数据库获取值并返回json对象的wcf服务。我尝试创建输入按钮取决于返回值:
$.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 :(得分: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());
});
})
答案 1 :(得分:0)
在警告而不是element.value
中将其更改为this.value
。如下所示,
element.onclick = function() { // Note this is a function
alert(this.value);
}