0

我有一个无序列表,其中包含从 JSON 文件中获取的客户名称。我想添加一个点击事件,但 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 文件中填充客户姓名的列表项中的文本不是真正的字符串(?)。或类似的东西。有人可以帮忙吗?

4

1 回答 1

3

当您没有 尝试使用所有li元素 时,您可能正在绑定事件

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

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

$('#customers').on('click', 'li', function() {
    console.log($(this).text());
});
于 2013-07-25T14:30:17.077 回答