Click event for elements added to DOM dynamically

2019-02-10 16:00发布

Before jQuery 1.8 I was able to use .live() to fire when a button was clicked that was dynamically inserted by jquery.

Now, .on() and .bind() both do not work for elements added to DOM after the page was loaded.

What are the options now?

标签: jquery dom click
2条回答
疯言疯语
2楼-- · 2019-02-10 16:40
$(parent_element).on("click", child_selector, function(evt) {
});

http://api.jquery.com/on/#direct-and-delegated-events

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.

查看更多
一纸荒年 Trace。
3楼-- · 2019-02-10 16:47

delegate is far efficient than on handler

$(document).delegate('click', "selector", function() {
    //your stuff
});
查看更多
登录 后发表回答