3

我正在使用stopwatch我在这里找到的代码:http: //www.kellishaver.com/projects/stopwatch/

(function($) {
    $.fn.stopwatch = function() {
        var clock = this;
        var timer = 0;

        clock.addClass('stopwatch');

        //console.log(clock);

        // This is bit messy, but IE is a crybaby and must be coddled. 
        clock.html('<div class="display"><span class="hr">00</span>:<span class="min">00</span>:<span class="sec">00</span></div>');
        clock.append('<input type="button" class="start" value="Start" />');
        clock.append('<input type="button" class="stop" value="Stop" />');
        clock.append('<input type="button" class="reset" value="Reset" />');

        //console.log(clock.html());

        // We have to do some searching, so we'll do it here, so we only have to do it once.
        var h = clock.find('.hr');
        var m = clock.find('.min');
        var s = clock.find('.sec');
        var start = clock.find('.start');
        var stop = clock.find('.stop');
        var reset = clock.find('.reset');

        stop.hide();

        start.bind('click', function() {
            timer = setInterval(do_time, 1000);
            stop.show();
            start.hide();
        });

        stop.bind('click', function() {
            clearInterval(timer);
            timer = 0;
            start.show();
            stop.hide();
        });

        reset.bind('click', function() {
            clearInterval(timer);
            timer = 0;
            h.html("00");
            m.html("00");
            s.html("00");
            stop.hide();
            start.show();
        });

        function do_time() {
            // parseInt() doesn't work here...
            hour = parseFloat(h.text());
            minute = parseFloat(m.text());
            second = parseFloat(s.text());

            second++;

            if(second > 59) {
                second = 0;
                minute = minute + 1;
            }
            if(minute > 59) {
                minute = 0;
                hour = hour + 1;
            }

            h.html("0".substring(hour >= 10) + hour);
            m.html("0".substring(minute >= 10) + minute);
            s.html("0".substring(second >= 10) + second);
        }
    };
})(jQuery);

我像这样使用它:

<script type="text/javascript">
    $('#clock1').stopwatch();
</script>

它工作正常,我可以使用停止按钮停止它。但是我希望能够使用 javascript 以编程方式停止它。像这样的东西:

<script type="text/javascript">
    $('#clock1').stop();
</script>

我创建了函数stop,但无法访问. 我该怎么做?timerstopwatch()

4

2 回答 2

5

怎么样:

$('#clock1').find('.stop').trigger('click');
于 2012-04-08T18:25:06.383 回答
4

您可以在代码中添加一个小 API 并使用以下方法附加它$.data

var api = {
    stop: function() {
        stop.click(); // this should probably be improved, but you get the idea
    }
 };
 $(clock).data('stopwatch', api);

然后使用:

$('#clock1').data('stopwatch').stop();

您还可以使用相同的逻辑将reset和函数添加到 API。start这里的一件好事是,您可以稍后在茶歇时改进执行代码,而无需更改外部程序使用 API 的方式。

于 2012-04-08T18:43:43.317 回答