jQuery 'on' not registering in dynamically generated modal popup

前端 未结 2 1959
你的背包
你的背包 2021-02-14 18:22

I was under the impression that jQuery\'s on event handler was meant to be able to \'listen\' for dynamically created elements AND that it was supposed to replace the behavior o

相关标签:
2条回答
  • 2021-02-14 18:48

    The problem is that the element to which you attach the event has to exist.

    You have to use on like this to capture clicks on p tags created dynamically

    $("#existingContainerId").on("click", "p", function(){
        alert( $(this).text() );
    });
    

    if you have no relevant existing container to use, you could use $("body") or $(document)

    If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.

    When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

    Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next

    Take a look to section Direct and delegated events here for more details

    0 讨论(0)
  • 2021-02-14 18:57

    live delegates the event from document object, but on doesn't, if you want to delegate the event using on method, you should delegate the event from one of static parents of the element or document object:

    $(document).on("click", ".clickHandle", function() {
        alert("Content clicked");
    });
    
    0 讨论(0)
提交回复
热议问题