我想調用一個函數,該函數在具有相同類的元素的節點列表上進行切換。我基本上需要在if語句中添加函數,但是這種不同的變體似乎會引發錯誤。當我將兩個函數內部的代碼直接放入if語句中時,它的工作原理就是這樣,但我想用函數來完成它,因爲這是一個簡化的版本,它將是更復雜的樣式更改。單擊某個事件時切換單個函數 - Javascript
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>