正常情况:
JSON解析错误:
改正后的代码:
$("#getdata").on("click",function() {
getdata();
});
$("tbody").on("click", ".getid", function() {
var jsonstr = decodeURIComponent($(this).parent().parent().parent().attr("dataentity"));
var selectedEntity = JSON.parse(jsonstr);
alert("id:" + selectedEntity.ID);
});
function getdata(parameters) {
$.ajax({
type: 'POST',
url: "Controller/Handler1.ashx",
async: true,
data: "function=theFunction" ,
dataType: 'json',
success: function(jsonObj) {
if (jsonObj.success) {
$("tbody").empty();
for (var i = 0; i < jsonObj.data.length; i++) {
var button = "<div><input type=\"button\" value=\"获取ID\" class=\"getid\"/></div>";
$("<tr dataentity=\"" + encodeURIComponent(JSON.stringify(jsonObj.data[i])) + "\">"
+ "<td>"
+jsonObj.data[i].ID
+ "</td>"
+ "<td>"
+ jsonObj.data[i].col1
+ "</td>"
+ "<td>"
+ jsonObj.data[i].col1
+ "</td>"
+ "<td>"
+ button
+ "</td>"
+"</tr>").appendTo($("tbody"));
}
} else {
window.alert(jsonObj.msg);
}
}
});
}
改正后的结果: