jQuery on load of dynamic element

自闭症网瘾萝莉.ら 提交于 2019-11-27 17:59:43

You can trigger a custom event on the newly added DOM element that can be picked-up by a jQuery event handler:

//bind to our custom event for the `.sub-element` elements
$('#container').on('custom-update', '.sub-element', function(){
    $(this).html('<b>yaay!</b>');
});

//append a new element to the container,
//then select it, based on the knowledge that it is the last child of the container element,
//and then trigger our custom event on the element
$('#container').append('<div class="sub-element">No worky!</div>').children().last().trigger('custom-update');

Here is a demo: http://jsfiddle.net/ggHh7/4/

This method allows you to do something globally even if you load the dynamic content through different methods.

Update

I'm not sure of the browser support (I'll assume IE8 and older don't support this) but you can use the DOMNodeInserted mutation event to detect when a DOM element is added:

$('#container').on('DOMNodeInserted', '.sub-element', function(){
    $(this).html('<b>yaay!</b>');
})

$('#container').append('<div class="sub-element">No worky!</div>');

Here is a demo: http://jsfiddle.net/ggHh7/7/

UPDATE

There is a new API for this as DOMNodeInserted is depreciated at this time. I haven't looked into it but it's called MutationOvserver: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

After reading the above answer I now use this successfully:

$('body').on({
   DOMNodeInserted : function(){
      alert('I have been added dynamically');
   },
   click : function(){
      alert('I was clicked');
   },
   '.dynamicElements'
});

Now all my dynamicElements can do stuff as they're loaded, utilizing the awesome .on() event map.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!