【问题标题】:Multiple Buttons Each with Unique Counter多个按钮,每个按钮都有唯一的计数器
【发布时间】:2021-06-19 17:10:39
【问题描述】:

所以我动态地创建了许多按钮,并且我想为每个按钮创建一个单独的计数器。我不确定如何区分按钮,因为它们最终都会具有相同的变量和 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
    ...
<% } %>

【问题讨论】:

    标签: javascript html dom dom-events ejs


    【解决方案1】:

    需要去掉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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多