简体   繁体   中英

Adding event listeners to buttons created from an array

I'm creating buttons out of "tags" taken from my database. I'd like to add mouse event listeners to each button. However, the listener only seems to work on the last created button. Any ideas? Thanks.

var tagsContainer = document.getElementById('tags');
var tagarray = placetags.split(" ");
for (var tagcounter = 0; tagcounter < tagarray.length; tagcounter++){
  var tag = document.createElement('input');
  tag.type = 'button';
  tag.value = tagarray[tagcounter];
  tag.id = 'tagbutton';
  tagsContainer.appendChild(tag);
  tag.addEventListener('mouseover' , function(){
    tag.style.color = 'white';
  });
  tag.addEventListener('mouseout' , function(){
    tag.style.color = 'orange';
  });
}

You need to change your handlers from this

tag.addEventListener('mouseover' , function(){
    tag.style.color = 'white';
});

to this

tag.addEventListener('mouseover' , function(){
    this.style.color = 'white';
});

Since with your original code, your handlers are closing over the tag variable, and so tag ends up referring to the last button created.

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