使用下面的代码,当我单击并按住bid-up
按钮时,它只会通过代码一次,我必须再次单击它才能工作。它应该做的是重复代码直到mouseup或mouseleave。我做错了什么?
$('.bid-up').live('mousedown',function() {
var button = $(this);
timeoutId = setTimeout(function(){
var number = button.parent('div').siblings('#bid-child-container-2').find('#bid-price').val();
var newnumber = number.split('.');
var on = button.attr('data-on');
button.siblings('#bid-down').attr('data-on','1');
if(newnumber[1]<9) {
var first = newnumber[0];
var second = parseInt(newnumber[1])+1;
}
if(newnumber[1]==9) {
var first = parseInt(newnumber[0])+1;
var second = 0;
}
var finalnumber = first+'.'+second;
button.parent('div').siblings('#bid-child-container-2').find('#bid-price').val(finalnumber);
}, 20);
}).bind('mouseup mouseleave', function() {
clearTimeout(timeoutId);
});
答案 0 :(得分:2)
解决方案:使用setInterval
和clearInterval
而不是超时,因为setTimeout只执行一次闭包函数,或者在闭包函数中执行setTimeout
。
在函数本身中使用setTimeout
的示例:
$('.bid-up').live('mousedown',function() {
var button = $(this);
function asd(){
var number = button.parent('div').siblings('#bid-child-container-2').find('#bid-price').val();
var newnumber = number.split('.');
var on = button.attr('data-on');
button.siblings('#bid-down').attr('data-on','1');
if(newnumber[1]<9) {
var first = newnumber[0];
var second = parseInt(newnumber[1])+1;
}
if(newnumber[1]==9) {
var first = parseInt(newnumber[0])+1;
var second = 0;
}
var finalnumber = first+'.'+second;
button.parent('div').siblings('#bid-child-container-2').find('#bid-price').val(finalnumber);
timeoutId = setTimeout(asd, 20);
}
timeoutId = setTimeout(asd, 20);
}).bind('mouseup mouseleave', function() {
clearTimeout(timeoutId);
});
使用setInterval
和data
存储间隔ID的示例。
$('.bid-up').live('mousedown',function() {
var button = $(this);
button.data('interval', setInterval(function (){
var number = button.parent('div').siblings('#bid-child-container-2').find('#bid-price').val();
var newnumber = number.split('.');
var on = button.attr('data-on');
button.siblings('#bid-down').attr('data-on','1');
if(newnumber[1]<9) {
var first = newnumber[0];
var second = parseInt(newnumber[1])+1;
}
if(newnumber[1]==9) {
var first = parseInt(newnumber[0])+1;
var second = 0;
}
var finalnumber = first+'.'+second;
button.parent('div').siblings('#bid-child-container-2').find('#bid-price').val(finalnumber);
}, 20));
}).bind('mouseup mouseleave', function() {
clearInterval(button.data('interval'));
});
答案 1 :(得分:1)
试试这个: http://jsfiddle.net/R85Xb/
var timeoutId;
function x()
{
$("#bids").append("x");
timeoutId = setTimeout(x, 200);
}
$('.bid-up').live('mousedown', function() {
var button = $(this);
timeoutId = setTimeout(x, 200);
}).bind('mouseup mouseleave', function() {
//alert('clear');
clearTimeout(timeoutId);
});
<div class="bid-up">here</div>
<div id="bids"></div>