jquery detecting div of certain class has been added to DOM

前端 未结 6 1745
失恋的感觉
失恋的感觉 2020-12-02 06:49

I\'m using .on() to bind events of divs that get created after the page loads. It works fine for click, mouseenter... but I need to know when a new div of class

6条回答
  •  爱一瞬间的悲伤
    2020-12-02 07:36

    Here is my plugin that does exacly that - jquery.initialize

    Useage is the same like you'd use .each function, but with .initialize function on element, difference from .each is it will also initialize elements added in future without any additional code - no matter if you add it with AJAX or anything else.

    Initialize have exacly the same syntax as with .each function

    $(".some-element").initialize( function(){
        $(this).css("color", "blue");
    });
    

    But now if new element matching .some-element selector will appear on page, it will be instanty initialized. The way new item is added is not important, you dont need to care about any callbacks etc.

    $("
    ").addClass('some-element').appendTo("body"); //new element will have blue color!

    Plugin is based on MutationObserver

提交回复
热议问题