基于data-speed属性实现多计数器独立持续递增的技术需求
Fixing Multiple Independent Counter Increments
Hey there! Let's get your multiple counters working properly—right now your code has a few issues that prevent independent counting, but we can fix that easily while making sure new counters work without extra JS code.
First, let's spot the problems in your current code:
- Duplicate
idattributes: You have two elements withid="money"—HTML requires ids to be unique, so this will break element selection. - Single global
countervariable: All counters share the same value, so they can't increment independently. - Only reads the first counter's speed:
$(".countup").attr("data-speed")only grabs the speed from the first matching element, not each individual counter. - String-based interval call: Using
setInterval("countUP()", 1000)is not best practice; we should pass the function directly.
Here's the improved implementation:
Updated HTML (fix the duplicate ids):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="icon"></div> <div class="countup" data-speed="100">0</div> <div class="text">Let's count up</div> </div> <div class="container"> <div class="icon"></div> <div class="countup" data-speed="300">0</div> <div class="text">Let's count up differently</div> </div>
Updated JavaScript (independent counting + auto-detect new counters):
$(document).ready(function() { // Initialize each counter with its starting value $(".countup").each(function() { $(this).data("current-value", parseInt($(this).text())); }); // Set up the interval to update all counters every second setInterval(function() { $(".countup").each(function() { const $counter = $(this); const speed = parseInt($counter.attr("data-speed")); let currentValue = $counter.data("current-value"); // Increment the value currentValue += speed; // Update the stored value and display it with locale formatting $counter.data("current-value", currentValue); $counter.text(currentValue.toLocaleString("en")); }); }, 1000); });
How this works:
- Per-counter state: We use jQuery's
.data()to store each counter's current value individually, so they don't interfere with each other. - Auto-detect counters: Every time the interval runs, it loops through all
.countupelements—so if you add a new container with a.countupelement anddata-speedattribute later, it will automatically start incrementing without any JS changes. - Unique element handling: No more duplicate ids, since we target elements by their class instead.
Bonus: If you add counters dynamically later
Even if you add a new .countup element after the page loads (e.g., via AJAX), just make sure to initialize its current-value data when you add it:
// Example: Adding a new counter dynamically const newCounter = $('<div class="countup" data-speed="200">0</div>'); newCounter.data("current-value", 0); $(".some-container").append(newCounter);
内容的提问来源于stack exchange,提问作者Dan Chapman
相关产品推荐
相关产品推荐

