文章加密

;

2019年4月30日 星期二

click function not working after ajax →.on 是一種委託事件

当用ajax载入后端资料,並用js重新繪製table及其內的button後,原本放在$(funtion(){....})下的jQuery click function 就不執行了

The problem is that .click only works for elements already on the page. You have to use something like on if you are wiring up future elements.


所以應該把

$('.del').click(function(){
    alert("刪除");
});
改成

$(document).on("click",".del", function(){
  alert("刪除");
});

.on 是一種委託事件(delegate event),Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.

On a side note in the earlier versions of jQuery instead of .on() we used .live() or .delegate() functions.
參考: https://aiocollective.com/blog/click-doesn-t-work-after-ajax-load-jquery/

沒有留言:

張貼留言