简体   繁体   English

将事件侦听器添加到从数组创建的按钮中

[英]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. 由于使用原始代码,您的处理程序将关闭 tag变量,因此tag最终引用创建的最后一个按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM