无法用jquery读取json项

时间:2013-07-25 14:23:19

标签: jquery json html-lists

我有一个无序列表,其中包含我从JSON文件中获取的客户名称。我想添加一个click事件,但jQuery似乎无法读取它。该列表在HTML源文件中看起来很好,但列表项不会显示在console.log中。手动添加的虚拟客户处理点击事件就好了。

HTML

<ul id="customers">
    <li>Dummy customer</li><!-- manually added as a test -->
</ul>

JS(填写无序列表)

var getCustomers = 'json_webservice_api_I_can't_share';
$.getJSON( getCustomers )
.done(function( data ) {
    for(var i = 0; i < data.length; i++) {
        $('#customers').append('<li>' + data[i].Name + '</li>');
    }
});

JS(点击事件)

$('#customers li').click(function() {
    console.log($(this).text());
}

我猜测列表项中填充了JSON文件中客户名称的文本是不是真正的字符串(?)。或类似的东西。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

如果您没有所有 li 元素,则可能会对事件具有约束力

试试

$(document).on('click', '#customers li', function() {
    console.log($(this).text());
});

也可以这样做,也许是更好的方式(参见Jan Dvorak评论)

$('#customers').on('click', 'li', function() {
    console.log($(this).text());
});