3
我的當前設置加載在這一點我通過jQuery創建點擊事件,像這樣的動態列表:如何將jquery Click事件應用於動態列表元素?
$('#listReports li').click(function() {
var selected = $(this).text();
alert("List Item: " + selected);
});
我有代碼,允許用戶保存其被附加到列表的報告。在我再次調用函數之前,列表中的新項目不會觸發單擊事件。問題在於舊的項目事件被觸發兩次。
這是我如何追加我的列表項,並調用然後再次發揮作用:
$("#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);
});
}
}
});
有沒有辦法只能定義一次點擊事件並將其影響追加到列表中的新項目?
的作品太好了!現場和委託有什麼區別?一個比另一個更好嗎? – Paul
http://stackoverflow.com/search?q=jquery+live+vs+delegate –
[.live()](http://api.jquery.com/live/)在jQuery 1.7+中已棄用。改爲使用[.on()](http://api.jquery.com/on/) – rawbeans