简体   繁体   中英

How to add a listener to a div that is created after page load?

I have looked up other similar questions here and it looks like event delegation using on() is sort of in the direction I need.

I have an anchor which a user clicks to generate a dropdown menu. The menu, through css, appears below the link, but in the DOM the new div for the dropdown is generated outside of the 'scope' of the div in which the anchor resides. So it's something like this:

Before selection:

<body>
    <div>
        <!-- load of other nested divs -->
        <div class="menu">
            <a href="#" id="clickAnchor">Select from this list</a>
        </div>
    </div>
</body>

After selection:

<body>
    <div>
        <!-- load of other nested divs -->
        <div class="menu">
            <a href="#" id="clickAnchor">Select from this list</a>
        </div>
    </div>
    <div class="selected">
        <ul>
            <li>...</li>
            <!-- lots of these -->
        </ul>
</body>

I used <!-- load of other nested divs --> to indicate that 'menu' is nested deep within the first body div.

What I want to do is when 'selected' appears I want to append another class to it. This is so I can reuse the dropdown menu in other places. But I can't access this class for one or both of two reasons:

1] It's added dynamically so my jquery to add the class to it has finished running on page load. I can't use $(".selected").on("click", function(event){} as I am not clicking 'selected', rather I am clicking 'clickAnchor', so I am unsure how to access 'selected' this way.

2] Following from above, when I have tried $("#clickAnchor").on("click", function(event){} nothing is happening either - is this because the new div is created as a direct child of <body> , rather than as a child of 'menu'? In other words is it something to do with the scope of the click event? (Probably completely wrong here).

Attempt at a mockup for if you don't have control over appending the div.

$("#clickAnchor").on("click", function() {
    // code to append the div
    setTimeout(function() {
        var div = $(".selected");
        // add your code to add the class
    }, 0);
});

If you set a timeout to 0ms, it'll get queued to execute after the DOM has catched up with inserting the div, so you should be able to just select it. Alternatively, can you put a promise on the execution of the select2.js script? then you won't need the timeout.

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