0

我正在尝试创建类似'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');
    }); 
};
4

2 回答 2

5

不要再次声明此变量,只需删除var; var您正在使用关键字创建此变量的本地副本。该语句在该特定函数中本地创建变量。

 typingTimer = setTimeout(function(){
于 2013-07-29T11:40:50.747 回答
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对象中,然后这些变量可能会被其他脚本块覆盖。

于 2013-07-29T11:55:55.573 回答