多个按钮,每个按钮都有唯一的计数器
Multiple Buttons Each with Unique Counter
所以我动态创建了一些按钮,我想为每个按钮制作一个单独的计数器。我不确定如何区分按钮,因为它们最终都将具有相同的变量和 ID。这是我目前所拥有的:
<script>
let count = 0;
function addOne() {
count += 1
document.getElementById("count").innerHTML = count
}
</script>
<% for (let ele of elements) { %>
...
// More html elements
...
<button onclick="addOne()" type="button">Click Here!</button>
<span id="count">0</span>
...
// More html elements
...
<% } %>
你需要去掉span的id属性,它们不能同时相同
<% for (let ele of elements) { %>
<button onclick="addOne(this)" type="button">Click Here!</button>
<span>0</span>
<% } %>
function addOne(button) {
console.log(button.nextElementSibling.innerHTML)
var spanEle = button.nextElementSibling;
var old = parseInt(spanEle.innerHTML)
spanEle.innerHTML = old + 1;
}
所以我动态创建了一些按钮,我想为每个按钮制作一个单独的计数器。我不确定如何区分按钮,因为它们最终都将具有相同的变量和 ID。这是我目前所拥有的:
<script>
let count = 0;
function addOne() {
count += 1
document.getElementById("count").innerHTML = count
}
</script>
<% for (let ele of elements) { %>
...
// More html elements
...
<button onclick="addOne()" type="button">Click Here!</button>
<span id="count">0</span>
...
// More html elements
...
<% } %>
你需要去掉span的id属性,它们不能同时相同
<% for (let ele of elements) { %>
<button onclick="addOne(this)" type="button">Click Here!</button>
<span>0</span>
<% } %>
function addOne(button) {
console.log(button.nextElementSibling.innerHTML)
var spanEle = button.nextElementSibling;
var old = parseInt(spanEle.innerHTML)
spanEle.innerHTML = old + 1;
}