jquery数字计数器与jquery移动

时间:2011-09-29 22:29:29

标签: jquery jquery-mobile

我有一个从0到指定数字的代码,并在计数时显示它。 问题是我想在使用jQuery mobile制作的Web应用程序中使用代码。 当代码与普通的html一起使用时,我的工作正常,但是当我使用它与jQuery mobile时它不会工作。 我不希望数字开始计数,直到加载某个移动页面,有没有办法做到这一点? 我认为问题是因为在jquery mobile中,所有页面都包含在一个html文档中,当html页面打开时,数字会开始计数,我希望它在显示“#about”部分时启动?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
$(function() {
    $('#foo').counter({
        start: 1000,
        end: 400000,
        time: 1,
        step: 50,
        callback: function() {
            $("#foo").html("400000");
        }
    });
});

;(function($) {        
     $.fn.counter = function(options) {


        var options   = $.extend(defaults, options);

        var counterFunc = function(el, increment, end, step) {
            var value = parseInt(el.html(), 10) + increment;
            if(value >= end) {
                el.html(Math.round(end));
                options.callback();
            } else {
                el.html(Math.round(value));
                setTimeout(counterFunc, step, el, increment, end, step);
            }
        }

        $(this).html(Math.round(options.start));
        var increment = (options.end - options.start) / ((1000 / options.step) * options.time);

        (function(e, i, o, s) {
            setTimeout(counterFunc, s, e, i, o, s);
        })($(this), increment, options.end, options.step);
    }
})(jQuery);
    </script>
    <style type="text/css">
    </style>
</head>

<body>
    <span id="foo"></span>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

查看jQuery Mobile的事件文档:http://jquerymobile.com/demos/1.0rc1/docs/api/events.html

您希望在document.ready上运行代码,而不是在pageshow上运行代码。

变化:

$(function() {
    $('#foo').counter({
        start: 1000,
        end: 400000,
        time: 1,
        step: 50,
        callback: function() {
            $("#foo").html("400000");
        }
    });
});

要:

$(document).delegate('#about', 'pageshow', function() {
    $('#foo').counter({
        start: 1000,
        end: 400000,
        time: 1,
        step: 50,
        callback: function() {
            $("#foo").html("400000");
        }
    });
});

我没有使用过“计数器”插件,所以我不知道怎么做,但你可能想在用户导航到另一个页面时停止计数器,这样做只需绑定任何代码就可以将计数器停在pagehide事件:

$(document).delegate('#about', 'pagehide', function () {
    //code to stop counter goes here
});

A注意:我在上面的示例中使用了.delegate()函数,当$(document)对象上使用时,.live()函数就像$(document).delegate('#about', 'event-name', function () {});函数一样:

$(#about).live('event-name', function () {});.delegate()类似,但{{1}}执行效率更高。代表的文档在这里:http://api.jquery.com/delegate/