如何使 jquery 计数器与来自 innerHTML 的数据一起工作

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


下面我将计数器代码应用于.count类的所有元素,并且我希望这个计数器div使用 id = "users" 使用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,但这是出乎意料的。我有几个类的元素count依赖于这个计数器。


对此的任何帮助将不胜感激。


米琪卡哇伊
浏览 216回答 3
3回答

ABOUTYOU

@Ben you need to set the innerHTML before you call the counter animation&nbsp;document.getElementById('users').innerHTML = 300;$('.count').each(function () {&nbsp; &nbsp; &nbsp; &nbsp; $(this).prop('Counter',0).animate({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Counter: $(this).text()&nbsp; &nbsp; &nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; duration: 5000,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; easing: 'swing',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; step: function (now) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(this).text(Math.ceil(now));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript