[英]Using jQuery .on vs. using .live?
一個簡單的問題,因為jQuery .live()的1.7版已被棄用,而推薦使用.on();。 但是.on()似乎不適用於通過JavaScript渲染並加載到DOM中的元素。 所以我的問題是,仍然應該使用.live()還是.on()如何捕獲這些新生成的元素?
例如,這是我的代碼:
$("#listitem").append("<li id='removeitem'>" +
formdata + ' <a href="#">Remove</a></li>');
當我嘗試通過.on()對這個元素進行操作時-結果什么都沒有,而.live()能夠抓取這個元素。
$("#removeitem").live("click", function(event) { alert($(this).text()); });
live
版:
$("#removeitem").live("click", function(event) { alert($(this).text()); });
應該更改為:
$("#containerId").on("click", "#removeitem", function(event) {
alert($(this).text());
});
其中containerId
是removeitem
加載到的靜態元素。
您可以簡單地將body
用作靜態元素:
$("body").on('click', '#removeitem'm fn);
但是代碼的效率會降低,只需嘗試使用它來演示其工作原理。
筆記:
id
元素,因為它是無效的標記。 listitem
是代碼中的靜態元素。 更新:
也許那是我的問題-我只是將.live替換為.on
您不能簡單地替換它們...它們以其他方式工作,並且具有不同的參數!
閱讀每個功能的文檔:
on
:
.on(events [, selector] [, data], handler(eventObject))
.live( events, handler(eventObject) )
您應該嘗試使用.on()
這樣:
$('#listitem').on('click', '#removeitem', function() {
alert($(this).text());
});
如果您沒有諸如removeitem
類的固定ID,並且其結構如removeitem1
, removeitem1
等,則嘗試:
$('#listitem').on('click', '[id^=removeitem]', function() {
alert($(this).text());
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.