简体   繁体   中英

How do I add events to array elements?

My code

var boxes = document.getElementsByClassName("box");
for(var i=0; i<boxes.length;i++)
{
    boxes[i].addEventListener("dblclick", function(e){
        this.classList.add("animateSize");
        this.style.width="2px";
        this.style.height="2px";
        window.setTimeout(2000);
    });
}

Initially I have only one box, then I create more boxes but when I double click any of the newly created boxes nothing happens, only when I double click the initial box the event is triggered.

What am I doing wrong?

PS. When I alert(boxes.length) after I've created, lets say 4 boxes, I get the correct length alerted(5=4 + 1 initial box).

Trouble is your code only attaches event handlers for the matches that are currently loaded in the DOM. If this is on DOM load, no 'future' elements will have the event attached.

You could listen for a double click on a static container (I've gone for document) and make a check to see whether the element targeted had the class box . If so, carry out your code:

document.addEventListener("dblclick", function(e){
    if(e.target.classList.contains('box')){
        var box = e.target;
        box.classList.add("animateSize");
        box.style.width="2px";
        box.style.height="2px";
        window.setTimeout(2000);
    }
});

Also known as event delegation.

Note that you'd want to change document for closest static container of your boxes.

There are other ways of course, like attaching your event handlers every time you add your nodes to the DOM.

JSFiddle

You need some kind of event delegation. Do this instead.

var parentElem = document.getElementsByClassName("box")[0].parentNode;
parentElem.attachEventHandler("dblclick", function(e) {
    var that = e.target;
    that.classList.add("animateSize");
    that.style.width = "2px";
    // (...) More code
});

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