【发布时间】:2015-07-22 17:58:28
【问题描述】:
我正在尝试使用 javascript 和 jQuery 找出停止/开始按钮。我设置了一个 jsfiddle 来尝试理解它,但我无法让它工作:http://jsfiddle.net/kkx7m88c/
开始按钮应一次将每个框变为红色。停止按钮应将所有框恢复为蓝色,并停止再变为红色,直到再次按下开始按钮。目前,停止按钮会将所有框变为蓝色但不会停止播放功能,这意味着尚未变为红色的框不会停止。它们变成红色。
这是我的 js:
// new class turns the boxes red with css
function goClasses(item, container) {
$(container).removeClass('stopped');
$(item).addClass('new');
}
function stopClasses(item, container) {
$(item).removeClass('new');
$(container).addClass('stopped');
}
$('#go').mousedown(function () {
$('.box').each(function(i){
var item = $(this);
var container = $('.selection');
setTimeout(function () {
goClasses(item, container);
}, 500 * i);
if ($(container).hasClass('stopped')) {
//clearTimeout(); /* this doesn't appear to do anything */
//return false; /* this stops the 'go' button from working properly when clicked again after the 'stop' button has clicked */
}
});
});
$('#stop').mousedown(function () {
$('.box').each(function (i) {
var item = $(this);
var container = $('.selection');
stopClasses(item, container);
});
});
我的理解是,如果我可以结束 mousedown 部分中的 setTimeout 和 .each ,它会起作用......但也许我完全关闭了它。也许我应该改用 setInterval() ?我是 jQuery 新手,所以我还在搞清楚!
【问题讨论】:
-
我不认为你的问题出在计时器上,这是因为循环在进行。尝试从停止按钮设置一个标志并在启动函数中检查它以打破循环。
标签: javascript jquery html css