添加额外的按钮会导致代码无法工作



我想要一个按钮来更改单击时的颜色。当我只有一个按钮时,我的代码当前可以工作,但当我添加多个按钮时就会停止工作。我可以添加什么以使其适用于多个按钮?

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">Button 1</button>
<button id="btn">Button 2</button>

</body>
<script> 
let index = 0;
let textIndex = 0;
const colors = ['green', 'red'];
const text = ['GREEN', 'RED']
btn.addEventListener('click', function onClick() {
btn.style.backgroundColor = colors[index];
btn.style.color = 'white';
btn.textText = "yes";
btn.innerHTML = text[textIndex];
index = index >= colors.length - 1 ? 0 : index + 1;
textIndex = textIndex >= text.length - 1 ? 0 : textIndex + 1;
})
</script>
</html>```

Id必须是唯一的,这是您的第一个问题。使用一个类,然后使用querySelectorAll在该类上进行选择,并将事件侦听器绑定到这些元素。

最后,只需使用一个数组。我刚刚处理了数组中的文本,但对于更复杂的用例,可以使用对象数组。

let index = 0;
const colors = ['Green', 'Red'];

document.querySelectorAll(".btn").forEach(item => item.addEventListener('click', function onClick() {
/*this refers to the element clicke*/
this.style.backgroundColor = colors[index].toLowerCase();
this.style.color = 'white';
this.textText = "yes";
this.innerHTML = colors[index].toUpperCase();
index = index >= colors.length - 1 ? 0 : index + 1;    
}));
<button class="btn">Button 1</button>
<button class="btn">Button 2</button>

相关内容

最新更新