简体   繁体   English

动态创建的元素不响应“父级”点击事件

[英]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/ http://jsfiddle.net/LUsMb/607/

see test1 class and its' event function. 请参阅test1类及其事件函数。

(it's not my page, I found a jsfiddle select2 example on google and added my problem to it) (这不是我的页面,我在Google上找到了jsfiddle select2示例,并向其中添加了问题)

sorry for the slightly overcomplicated example, just look for test1 , it's in the html once and twice in the javascript. 对于稍微复杂的示例,我们感到抱歉,只需查找test1 ,它就在html中的javascript中出现了两次。

enter 'khglkgliy' in the search 在搜索中输入“ khglkgliy”

EDIT: this is a simpler example - enter something that's not in the list - http://jsfiddle.net/LUsMb/614/ 编辑:这是一个简单的示例-输入不在列表中的内容-http://jsfiddle.net/LUsMb/614/

Check your file select2.js line 682 检查文件select2.js第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: 我无法在您的jsFiddle中重现该问题(我看不到如何让jsFiddle实际创建任何新对象),但是您的.on()事件监听器有以下可能的原因:

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

wouldn't work for newly created elements: 不适用于新创建的元素:

  1. They aren't children of the #volatiles_container object. 它们不是#volatiles_container对象的子级。
  2. The newly created objects don't match the selector ".volatile" . 新创建的对象与选择器".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. 由于您的事件处理程序是当前应用于顶级文档的,因此我想这是第4个项目。 I'd suggest using an event handler that is as close to the dynamic element as possible as you can go. 我建议您使用一个尽可能接近动态元素的事件处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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