1

我正在尝试让这个 Jquery 计数功能正常工作,但它没有出现在我面前,有人可以告诉我我做错了什么吗?

我正在使用由“mhuggins”(https://github.com/mhuggins/jquery-countTo)创建的函数,所以我自己没有做到,只是想让它工作。

计数.js

    (function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});

        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;

        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);

            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));

                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }

                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;

                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };

    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 1000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null,  // callback method for when the element finishes updating
    };
})(jQuery);

然后我尝试将它与这个 html 页面一起使用

测试.html

<html>
<head>
<script type="text/javascript" src="scripts/jquery-1.6.2.js"></script>
<script type="text/javascript" src="scripts/countup.js"></script>
<script type="text/javascript"><!--
    $('.timer').countTo({from: 0, to: 500});
//--></script>
</head>

<body>
<span class="timer"></span>
</body>
</html>

当我启动页面时,什么也没有发生。该脚本对其他人有效,所以很明显是我做错了什么。我对此很陌生,所以这并不奇怪。

谢谢!

4

3 回答 3

4

看起来你不见了document.ready(function() { // timer code here });

于 2012-07-09T10:35:53.800 回答
2

<span class="timer">执行脚本时没有。将其添加为DOMready 处理程序

<script type="text/javascript"><!--
    jQuery(function($) {
        $('.timer').countTo({from: 0, to: 500});
    });
//--></script>
</head>

或在正文末尾执行:

<body>
    <span class="timer"></span>
    <script type="text/javascript"><!--
        $('.timer').countTo({from: 0, to: 500});
    //--></script>
</body>
于 2012-07-09T10:37:22.277 回答
1
$(document).ready(function(){
    $('.timer').countTo({from: 0, to: 500});
});
于 2012-07-09T10:37:32.157 回答