简体   繁体   中英

Dynamically created element doesn't respond to “parent” click event

First and foremost, I know I should use the following code to attach to volatile elements

$("#volatiles_container").on("click", ".volatile", function() { ... });

I know that.

But it doesn't work, see this demo, the existing works, the created doesn't, why?

http://jsfiddle.net/LUsMb/607/

see test1 class and its' event function.

(it's not my page, I found a jsfiddle select2 example on google and added my problem to it)

sorry for the slightly overcomplicated example, just look for test1 , it's in the html once and twice in the javascript.

enter 'khglkgliy' in the search

EDIT: this is a simpler example - enter something that's not in the list - http://jsfiddle.net/LUsMb/614/

Check your file select2.js line 682

this.dropdown.bind("click mouseup mousedown", function (e) { e.stopPropagation(); });

I am thinking that the click event is stopped here.

I can't reproduce the issue in your jsFiddle (I don't see how to get the jsFiddle to actually create any new objects), but there are these possible reasons that your .on() event listener:

$("#volatiles_container").on("click", ".volatile", function() { ... });

wouldn't work for newly created elements:

  1. They aren't children of the #volatiles_container object.
  2. The newly created objects don't match the selector ".volatile" .
  3. There are other objects on top of the newly created objects that are receiving the click events.
  4. Another click handler is stopping event propagation so that the event does not bubble up to the element that has the event handler on it.

Since your event handler is current applied at the top level document, I would guess that it's the 4th item. I'd suggest using an event handler that is as close to the dynamic element as possible as you can go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM