我正在尝试对多个按钮使用相同的“id”或“class”,以使用 javascript 递增计数 1。
下面的代码显示了如何通过单击一个按钮以 1 为增量进行计数,但不能与使用相同“id”的其他按钮一起使用。
为了帮助自己开始理解执行此操作的过程,我在线复制了使用 getElementById 的代码,您可以在下面看到。这段代码并没有达到我的目的,因为只有一个按钮添加到计数器,而不是另一个使用相同的“id”的按钮。理想情况下,我希望两个按钮仅使用一个“id”或一个“class”来添加到计数器。我想这样做是为了保持我的代码简短:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>COUNTER</title>
</head>
<body>
<h1>Counter</h1>
<div class="counter">
<button id="shopping-cart-add-on">+</button>
<button id="shopping-cart-add-on">+</button>
<div id="counter-value">0</div>
</div>
<script>
let counter = 0;
const counterValue = document.getElementById('counter-value');
const incrementBtn = document.getElementById('shopping-cart-add-on');
const incrementBtnTwo = document.getElementById('shopping-cart-add-on-two');
// To increment the value of counter
incrementBtn.addEventListener('click', () => {
counter++;
counterValue.innerHTML = counter;
});
incrementBtnTwo.addEventListener('click', () => {
counter++;
counterValue.innerHTML = counter;
});
</script>
</body>
</html>
根据我在网上收集的信息,“getElementById”不能按照我想要的方式多次使用。然后我研究了“getElementsByclassname”,希望使用“class”对多个按钮进行一计数。我还研究了 for 循环选项,但遇到了麻烦。
使用 javascript 使用一个“class”或“id”来计算多个按钮的最佳方法是什么?我试图保持我的 javascript 代码简短,而不必编写多个“id”或“classes”等。
谢谢
<h1>Counter</h1>
<div class="counter">
<button class="shopping-cart-add-on">+</button>
<button class="shopping-cart-add-on">+</button>
<div id="counter-value">0</div>
</div>
<script>
let counter = 0;
const counterValue = document.getElementById('counter-value');
const incrementBtn = document.querySelectAll('.shopping-cart-add-on');
// To increment the value of counter
incrementBtn.addEventListener('click', () => {
counter++;
counterValue.innerHTML = counter;
});
</script>