简体   繁体   中英

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. I'm also new to posting here on 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. 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):

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? I know I could loop through the DIVs and say:

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.

If you want the div with the class "div" to be clickable along with everything inside it then you just have to do:

$('.div').on('click', function () {
    //DO SOMETHING
});

The above will make the container div and everything inside clickable.

If you want all divs inside only to be clickable then you would do this:

$('.div div').on('click', function () {
    //DO SOMETHING
});

Here's a JSFiddle to demonstrate: http://jsfiddle.net/simonlevasseur/82m9Y/

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