简体   繁体   中英

Can't attach the event listeners to the dynamically created buttons

I need to add some buttons in my document and make them call getTest() function. So 1 button should call getTest(1) , the 2nd one - getTest(2) and so on. But once the script was completed, the event listener is only attached to the last button in the loop.

window.onload = function() {
        var button_place = document.getElementById("buttons_here"); // get an element

        /* add the event listeners */
        var i = 0;
        while(i < 10) {
            var cur_i = i + 1;
            var current_but_name = "but_" + (i + 1);
            button_place.innerHTML += "<button class=button id='" + current_but_name + "'>" + cur_i + "</button>\n";
            var bu = document.getElementById(current_but_name);
            //bu.style.color = "#F00";

            bu.addEventListener("click", function() {
                getTest(cur_i);
            });

            ++i;
        }
    }

How can I deal with it? How can I attach an event listener to the every button I created?

this is because the loop that attaches is syncronous, finishes and the value of cur_i is always the last value of the iterator when the click occurs. you need to wrap this into a local scope.

(function(cur_i){
    bu.addEventListener("click", function() {
        getTest(cur_i);
    });
}(cur_i));

this will ensure that the value is correct as of the time of binding.

you really should use document.createElement instead and attach the events directly to the element rather than passing through the DOM, which is slower.


also, innerHTML is immutable and every += you do, recreates the whole lot so on each iteration, you are destroying the old/previous elements and re-adding them but without their event handlers!

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