【问题标题】:Adding event listeners to buttons created from an array将事件侦听器添加到从数组创建的按钮
【发布时间】:2012-11-26 06:33:54
【问题描述】:

我正在使用从我的数据库中获取的“标签”创建按钮。我想为每个按钮添加鼠标事件监听器。但是,侦听器似乎只对最后创建的按钮起作用。有任何想法吗?谢谢。

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';
  });
}

【问题讨论】:

  • 这样的? jsfiddle.net/mjqWL/3
  • 谢谢。当然是一个简单的“this.style.color”而不是“tag.style.color”!
  • 对不起,我什至没有意识到我改变了这一点。亚当的回答解释了原因。
  • @Blender - 解决您的烦恼的徽章 :)
  • 请注意,您可以为所有按钮使用single event handler

标签: javascript arrays mouseevent createelement


【解决方案1】:

您需要从这里更改您的处理程序

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

到这里

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

由于使用您的原始代码,您的处理程序关闭标记变量,因此tag 最终引用了最后一个创建的按钮。

【讨论】:

  • 我仍然看到多个按钮。现在我只想做 mouseover / mouseout 事件。
猜你喜欢
  • 2019-07-03
  • 2021-03-21
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多