我正在尝试创建类似'onFinishTyping'的东西,它设置3s的超时,如果用户在3秒内写了一些东西,我需要销毁该计时器并设置新的..问题是每个按钮点击事件被触发后。
这就是我所拥有的:
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 3000; //time in ms
// Notice: jq = jQuery.noConflict();
jq(document).ready(function(){
//on keyup, start the countdown
jq('.table-search-field').keyup(function(event){
var typingTimer = setTimeout(function(){
doneTyping(event.target);
}, doneTypingInterval);
});
//on keydown, clear the countdown
jq('.table-search-field').keydown(function(){
clearTimeout(typingTimer);
});
});
//user is "finished typing," do something
function doneTyping (field) {
var value = jq(field).val().toLowerCase();// lower case
jq.ajax('index.php?option=com_mycomponent&task=player.search&keyword='+value)
.done(function(data){
console.log('ok');
}).fail(function(){
console.log('fail');
});
};
答案 0 :(得分:5)
不要再次声明此变量,只需删除var
;您正在使用var
关键字创建此变量的本地副本。该语句在该特定函数中本地创建变量。
typingTimer = setTimeout(function(){
答案 1 :(得分:3)
尝试使用闭包,以便超时变量在您使用它的函数范围内:
(function() {
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 3000; //time in ms
// Notice: jq = jQuery.noConflict();
jq(document).ready(function(){
//on keyup, start the countdown
jq('.table-search-field').keyup(function(event){
var typingTimer = setTimeout(function(){
doneTyping(event.target);
}, doneTypingInterval);
});
//on keydown, clear the countdown
jq('.table-search-field').keydown(function(){
clearTimeout(typingTimer);
});
});
//user is "finished typing," do something
function doneTyping (field) {
var value = jq(field).val().toLowerCase();// lower case
jq.ajax('index.php?option=com_mycomponent&task=player.search&keyword='+value)
.done(function(data){
console.log('ok');
}).fail(function(){
console.log('fail');
});
};
})();
不要只考虑建议删除var
而不考虑其含义,你不必将变量转储到window
对象中,然后可以被其他脚本块覆盖。