我正在使用我在此处找到的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
函数,但我无法访问timer
中定义的stopwatch()
var。我该怎么办?
答案 0 :(得分:5)
怎么样:
$('#clock1').find('.stop').trigger('click');
答案 1 :(得分: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
和start
函数添加到API。这里的一件好事是,您可以在以后改善咖啡休息时间的执行代码,而无需改变外部程序使用API的方式。