我想调用一个函数来切换具有相同类的元素的节点列表。我基本上需要在 if else 语句中添加该函数,但它的不同变体似乎会引发错误。当我将两个函数内的代码直接放入 if else 语句中时,它可以工作,但我想使用函数来完成此操作,因为这是更复杂的样式更改的简化版本。
Codepen在这里:https://codepen.io/emilychews/pen/GEEpqW?editors=1111
代码如下:
JS
var $mainMenuButton = document.getElementsByClassName('desktopmenubutton');
function newColor() {
e.currentTarget.style.background = "black";
}
function originalColor() {
e.currentTarget.style.background = "red";
}
for (h = 0; h < $mainMenuButton.length; h +=1) {
$mainMenuButton[h].addEventListener('click', function(e) {
if (e.currentTarget.style.backgroundColor === "red") {
newColor();
} else {
originalColor();
}
});
}
CSS
* {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;
}
HTML
<div class="desktopmenubutton button1">Button 1</div>
<div class="desktopmenubutton button2">Button 2</div>
最佳答案
传递 if
语句内函数中的元素。
var $mainMenuButton = document.getElementsByClassName('desktopmenubutton button1');
function newColor(element) {
element.currentTarget.style.backgroundColor = "black";
}
function originalColor(element) {
element.currentTarget.style.backgroundColor = "red";
}
for (h = 0; h < $mainMenuButton.length; h +=1) {
$mainMenuButton[h].addEventListener('click', function(e) {
if (e.currentTarget.style.backgroundColor === "red") {
newColor(e);
} else {
originalColor(e);
}
});
}
关于javascript - 单击事件时切换各个功能 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44684431/