Automatically add an event handler to a newly created element using jQuery

后端 未结 2 1348
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 14:52

On document ready I attach this event handler to all elements with class bubbleItemOff. My problem is that some of the bubbleItemOff elements are created dynamically after t

相关标签:
2条回答
  • 2020-12-19 15:25

    You can use jQuery on method in delegated-events approach:

    $(".parentItem").on("mouseenter", ".bubbleItemOff", function(e) {
        //
    });
    

    Here .parentItem refers to any parent of .bubbleItemOff.

    0 讨论(0)
  • 2020-12-19 15:28

    Use event delegation on a common parent element using on() method (assuming you're using jQuery 1.7.x +), e.g.

    $(function() {
        $('body').on('mouseenter', '.bubbleItemOff', function(e) 
        {
         ...
        }
    }
    

    if you're using an older version use delegate() instead. Change body with the first common parent element of .bubbleItemOff

    0 讨论(0)
提交回复
热议问题