[英]How do I associate a parent node with all of its children in an event listener? jQuery / JavaScript
I'm not extremely good with JavaScript, as I've only been coding as a hobby for a little over a year now, so forgive me if this question seems stupid. 我对JavaScript并不是特别擅长,因为我只是将编码作为一种兴趣才一年多,所以如果这个问题看起来很愚蠢,请原谅我。 I'm also new to posting here on StackOverflow.
我也是在StackOverflow上发布的新手。
Anyway, I'm trying to put an event listener on a dynamically created element that has child nodes. 无论如何,我试图将事件侦听器放在具有子节点的动态创建的元素上。
Example: 例:
<div class="div">
<div class="div2">
Content in Div2
</div>
<div class="div3">
Content in Div3
</div>
Content in Div
</div>
That would be the HTML setup. 那就是HTML设置。 For the JavaScript (I am using jQuery too, if there is a better way to handle this) I am using this code (because the elements are dynamically generated):
对于JavaScript(如果有更好的处理方法,我也使用jQuery),我正在使用此代码(因为元素是动态生成的):
document.querySelector('body').addEventListener('click',function(e){
if (e.target.className === "div"){
//Run this code
}
});
But what if I want to have that code run even when div2
and div3
are clicked? 但是,即使单击
div2
和div3
,我也想运行该代码怎么办? I know I could loop through the DIVs and say: 我知道我可以遍历DIV并说:
document.querySelector('body').addEventListener('click',function(e){
if (e.target.className === "div" || e.target.parentNode.className === "div"){
//Run this code
}
});
However my actual code has a lot of stuff going on and it would look like a jumbled mess. 但是,我的实际代码中发生了很多事情,看起来像是一团糟。 Is there a more optimal way to go about this?
有没有更好的方法来解决这个问题?
I feel like I'm missing something very simple 我觉得我缺少一些非常简单的东西
Since your elements are created during run time, they would not available while registering events for them in ready state, so that in this context you have to use event delegation 由于您的元素是在运行时创建的,因此在为就绪状态为其注册事件时将无法使用它们,因此在这种情况下,您必须使用事件委托
Try, 尝试,
$(document).on('click','[class^="div"]',function(){
//your code here.
});
And in the above code, i have used attribute starts with selector , so that you could easily select the elements which have class name starts with div and write the events for the same. 并且在上面的代码中,我使用了以selector开头的属性 ,因此您可以轻松地选择类名称以div开头的元素,并为其编写事件。
If you want the div with the class "div" to be clickable along with everything inside it then you just have to do: 如果要使带有“ div”类的div及其内部的所有内容都可单击,则只需执行以下操作:
$('.div').on('click', function () {
//DO SOMETHING
});
The above will make the container div and everything inside clickable. 上面的代码将使容器div和其中的所有内容均可点击。
If you want all divs inside only to be clickable then you would do this: 如果您只希望单击内部的所有div,则可以这样做:
$('.div div').on('click', function () {
//DO SOMETHING
});
Here's a JSFiddle to demonstrate: http://jsfiddle.net/simonlevasseur/82m9Y/ 这是一个JSFiddle来演示: http : //jsfiddle.net/simonlevasseur/82m9Y/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.