jQuery 'on' not registering in dynamically

2019-03-26 18:28发布

问题:

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 of live. However, what I have experienced is that using on is not capturing the click event whereas using live is succeeding!

The tricky aspect of my situation is that I am not only dynamically creating content but I'm doing it via an AJAX .get() call, and inserting the resultant HTML into a modal .dialog() jQueryUI popup.

Here is a simplified version of what I was trying to accomplish (wrapped in $(document).ready(...) ):

$.get("getUserDataAjax.php", queryString, function(formToDisplay) {
    $("#dialog").dialog({
        autoOpen: true,
        modal: true,
        buttons...
    }).html(formToDisplay);
});
$(".classThatExistsInFormToDisplay").on("click", function() {
    alert("This doesn't get called");
});

From the documentation for on I found this which which was how I was approaching writing my on event:

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

However, for some reason, live will work as I expect -- whereas on is failing me.

This isn't a question for "how can I make it work" because I have found that on will succeed (capture clicks) if I declare it inside the function(formToDisplay) callback.

My question is: what is wrong with on that it isn't finding my dynamically created elements within a modal popup? My jQuery instance is jquery-1.7.2. jQueryUI is 1.8.21.

Here are two jsFiddles that approximate the issue. Click the word "Test" in both instances to see the different behavior. The only difference in code is replacing on for live.

Where the click is captured by live.

Where the click is NOT captured by on (click 'Test - click me' to see nothing happen).

I realize I may just be using on inappropriately or asking it to do something that was not intended but I want to know why it is not working (but if you have something terribly clever, feel free to share). Thanks for your wisdom!

Update / Answer / Solution:

According to user 'undefined', the difference is that on is not delegated all the way from the top of the document object whereas live does/is.

As Claudio mentions, there are portions of the on documentation that reference dynamically created elements and that what you include in the $("") part of the query needs to exist at runtime.

Here is my new solution: Capture click events on my modal dialog, which, although it does not have any content when the event is created at runtime, will be able to find my content and element with special class that gets generated later.

$("#dialog").on("click", ".classThatExistsInFormToDisplay", function() {
    ... //(success! Event captured)
});

Thanks so much!

回答1:

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");
});


回答2:

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