如何使 jquery 计数器处理来自 innerHTML 的数据

How to make jquery counter work with data from innerHTML

我正在尝试使用 jquery 制作一个计数器。该计数器在数据直接传递到 div 时起作用,但在使用 .innerHTML 调用将此数据动态附加到 div 时不起作用。

下面我将计数器代码应用于 .count class 的所有元素,我希望此计数器在 ID = "users" 的 div 上使用document.getElementById('users').innerHTML = 300; 这行不通。

但以下工作:<div id="users" class="count">300</div>

$('.count').each(function () {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 5000,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.ceil(now));
            }
        });
     });
<div id="users" class="count"></div>

document.getElementById('users').innerHTML = 300; 

我在使用 document.getElementById('users').innerHTML = 300; 时得到的输出是 0,但这是意外的。我有几个 class count 的元素取决于此计数器。

如有任何帮助,我们将不胜感激。

您可能想在 .each 代码之前写 document.getElementById('users').innerHTML = 300;,因为 .innerHTML 适合我

document.getElementById('users').innerHTML = 300;
$('.count').each(function() {
  $(this).prop('Counter', 0).animate({
    Counter: $(this).text()
  }, {
    duration: 5000,
    easing: 'swing',
    step: function(now) {
      $(this).text(Math.ceil(now));
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="users" class="count"></div>

或者你可以添加 DOMSubtreeModified 事件,所以当子树改变时你的功能将被触发(one 是触发一次事件,因为我们不想要子树事件再次触发):

$('.count').one("DOMSubtreeModified", function() {
  $('.count').each(function() {
    $(this).prop('Counter', 0).animate({
      Counter: $(this).text()
    }, {
      duration: 5000,
      easing: 'swing',
      step: function(now) {
        $(this).text(Math.ceil(now));
      }
    });
  });
});
document.getElementById('users').innerHTML = 300;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="users" class="count"></div>

@Ben you need to set the innerHTML before you call the counter animation 
document.getElementById('users').innerHTML = 300;

$('.count').each(function () {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 5000,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.ceil(now));
            }
        });
     });

我不太确定 "I want this counter to work..." 是什么意思,但这是否适用于您的用例?:

const users = document.getElementById("users");
users.innerHTML = "300";
//users.addEventListener("change", console.log(users.innerHTML));

$('.count').each(function () {
  let num = users.innerHTML; // Sets the value dynamically
  $(this).prop('Counter', num).animate({
    Counter: $(this).text()
  }, {
    duration: 5000,
    easing: 'swing',
    step: function (now) {
      $(this).text(Math.ceil(now));
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="users" class="count">0</p>