我当前的设置加载了一个动态列表,此时我通过 jquery 创建了一个点击事件,如下所示:
$('#listReports li').click(function () {
var selected = $(this).text();
alert("List Item: " + selected);
});
我有代码可以让用户保存一份报告,该报告会附加到列表中。在我再次调用该函数之前,列表中的新项目不会触发点击事件。这个问题是对于较旧的项目,事件被触发了两次。
下面是我附加列表项并再次调用 then 函数的方法:
$("#save").click(function (e) {
if ($("#reportParams li").size()> 0) {
var fileName = $('#reportFileName').val();
if (!fileName) {
alert("You must enter a file name!");
}
else {
$('#listReports').append('<li><a href="#">'+fileName+'</a></li>');
$('#listReports li').click(function () {
var selected = $(this).text();
alert("List Item: " + selected);
});
}
}
});
有没有办法只定义一次点击事件并使其影响附加到列表的新项目?
最佳答案
代替 .click()
,使用 .live()
:
$('#listReports li').live('click', function ()
{
var selected = $(this).text();
alert("List Item: " + selected);
});
或.delegate()
:
$('#listReports').delegate('li', 'click', function ()
{
var selected = $(this).text();
alert("List Item: " + selected);
});
关于javascript - 如何将 jquery Click 事件应用于动态列表元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7968276/