Event not working on dynamically created element

后端 未结 1 1928
北海茫月
北海茫月 2020-12-06 20:49

I\'m pulling my hair out trying to figure out why the mouseover event won\'t work with the .on handler with a dynamically created element from ajax. The only thing that seem

相关标签:
1条回答
  • 2020-12-06 21:14

    Using .on for newly generated elements with dynamic event delegation http://api.jquery.com/on/ - where your main selector is an existent static parent:

    $(".static-parent").on("event1 event2", ".dynamic-child", function() {
    

    or in your case:

    $(".dropdown").on("mouseover", "li", function() {
       alert('mouseover works!!!!!!!!!');
    });
    

    Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

    Also make sure to use a DOM ready function

    jQuery(function($) { // DOM is now ready and $ alias secured
    
        $(".dropdown").on("mouseover", "li", function() {
           alert('mouseover works!!!!!!!!!');
        });
    
    });
    
    0 讨论(0)
提交回复
热议问题