Does jQuery.on() work for elements that are added

2018-12-31 04:04发布

I was under the impression all this time that .on() worked like .live() with regards to dynamically created elements (e.g. I use $('.foo').on('click', function(){alert('click')}); and then an element with the class foo is created due to some AJAX, now I'm expecting a click on that element to cause an alert). In practice, these weren't the results I got. I could be making a mistake, but could somebody help me understand the new way to achieve these results, in the wake of .on()?

Thanks in advance.

标签: jquery
2条回答
长期被迫恋爱
2楼-- · 2018-12-31 04:39

I think you face similar situation that i faced. this is quite a good solution for binding events withe elements generated later.

Binding Jquery Events On Elements Generated Through Other Events

查看更多
笑指拈花
3楼-- · 2018-12-31 04:59

.on() works with dynamically created elements if it is used properly. The jQuery doc does a pretty good job of describing it.

The way to use it for dynamic elements is to use this form:

$("static selector").on('click', "dynamic selector", fn);

The static selector must resolve to some object that is both an ancestor of your dynamic objects and is static - is present when you run this line of code and won't be removed or recreated.

The dynamic selector is a selector that matches your dynamic elements. They do not have to exist at the time the event handler is first installed and they can come and go as often as you want.

So, if "#container" matches a static ancestor and ".foo" matches your dynamic elements that you want click handlers on, you would use this;

$("#container").on("click", ".foo", fn);

If you really want to understand it, this is how the delegated event handling of .on() works. When you make the .on() call above, it attached a click event handler to the #container object. Sometime later when you click on a .foo object, there is no click handler on the actual .foo object so the click bubbles up the ancestor chain. When the click gets to the #container object, there is a click handler and jQuery looks at that handler and sees that this handler is only for objects where the original clicked-upon object matches the selector ".foo". It tests the event target to see if it does match that selector and if so, it calls the event handler for it.

The (now deprecated) .live() method worked by attaching all event handlers to the document object. Since the document object is an ancestor of every object in the document, they got delegated event handling that way. So, in the example above, these two are equivalent:

$(document).on("click", ".foo", fn);
$(".foo").live("click", fn);

But, attaching all delegated event handlers on the document sometimes created a serious performance bottleneck so jQuery decided that was a bad way to do it and it was better to require the developer to specify a static ancestor that was hopefully closer to the actual target object than the document object.

查看更多
登录 后发表回答