在onclick事件fiddle
中传递对象时出错(function() {
function a() {
var x = [{
"name": "main",
"data": {"name":'john'}
}, {
"name": "sub",
"data": {"name":'guru'}
}, {
"name": "lower",
"data": {"name":'jack'}
}]
for (var i = 0; i < x.length; i++) {
var data = "<span onclick='getInfo(" + x[i].data + ")'>main </span>";
data += "<span onclick='getInfo(" + x[i].data + ")'>sub </span>"
data += "<span onclick='getInfo(" + x[i].data + ")'>lower</span><br>"
$('#data').prepend(data);
}
}
a()
})()
答案 0 :(得分:2)
您应该将生成数据的方式更改为:
var data = "<span onclick='getInfo(" + JSON.stringify(x[i].data) + ")'>main </span>";
如果没有生成的HTML,请执行以下操作:
<span onclick="getInfo([object Object])">main </span>
答案 1 :(得分:1)
您尝试分配对象而不是其名称,以便导致错误。试试这种方式
for (var i = 0; i < x.length; i++) {
var data = "<span onclick='getInfo(\"" + x[i].data.name + "\")'>main </span>";
data += "<span onclick='getInfo(\"" + x[i].data.name + "\")'>sub </span>"
data += "<span onclick='getInfo(\"" + x[i].data.name + "\")'>lower</span><br>"
$('#data').prepend(data);
}
更好地使用Jquery
onclick功能,例如
for (var i = 0; i < x.length; i++) {
var data = "<span data-name='\"" + x[i].data.name + "\"' class='notify'>main</span>";
data += "<span data-name='\"" + x[i].data.name + "\"' class='notify'>sub </span>"
data += "<span data-name='\"" + x[i].data.name + "\"' class='notify'>lower</span><br>"
$('#data').prepend(data);
}
$(document).on('click', '.notify', function(e) { console.log($(this).attr('data-name')); });
或者作为@Nemanja Todorovic的建议你可以将Json转换为字符串
for (var i = 0; i < x.length; i++) {
var data = "<span data-info='\"" + JSON.stringify(x[i].data) + "\"' class='notify'>main</span>";
data += "<span data-info='\"" + JSON.stringify(x[i].data) + "\"' class='notify'>sub </span>"
data += "<span data-info='\"" + JSON.stringify(x[i].data) + "\"' class='notify'>lower</span><br>"
$('#data').prepend(data);
}
$(document).on('click', '.notify', function(e) { console.log($(this).attr('data-info')); });