如何在类节点列表上切换事件

时间:2017-06-21 14:23:12

标签: javascript loops events click

我正在尝试在类节点列表上切换javascript事件。我已经完成了下面问题的简化版本。

正在执行初始事件,但是将按钮切换回红色的第二个事件似乎不起作用? JS并链接到Codepen下面。

Codepen在这里:https://codepen.io/emilychews/pen/EXmzbd?editors=1010

JS

$Sheet1.$F$18:$F$21

1 个答案:

答案 0 :(得分:1)

您只需要一个事件监听器即可实现此功能。



var $mainMenuButton = document.getElementsByClassName('desktopmenubutton');


for (h = 0; h < $mainMenuButton.length; h += 1) {
  $mainMenuButton[h].addEventListener('click', function(e) {
    if (e.currentTarget.style.backgroundColor == "red" || e.currentTarget.style.backgroundColor == "") {
      e.currentTarget.style.backgroundColor = "black";
    } else {
      e.currentTarget.style.backgroundColor = "red";
    }
  });
}
&#13;
* {font-family: arial;}

.desktopmenubutton {
  width: 150px;
  height: 100px;
  background-color: red;
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white
}

.button2 {
  left: 300px;
}
&#13;
<div class="desktopmenubutton button1">Button 1</div>
<div class="desktopmenubutton button2">Button 2</div>
&#13;
&#13;
&#13;