2015-02-08 59 views
0

我想和事件发射器在输入时有一点点延迟(冷却时间),例如1秒输入输入,所以输入一个字会触发多次,但只有1第二个最后的击键了解自定义JQuery事件以及如何修改它slrthly

后,我发现这个代码

$.fn.changeOrDelayedKey = function(fn, iKeyDelay, sKeyEvent) { 
    var iTimeoutId, 
     oEventData; 

    // second signature used, update the variables 
    if (!$.isFunction(fn)) { 
     oEventData = arguments[0]; 
     fn = arguments[1]; 
     iKeyDelay = arguments[2]; 
     sKeyEvent = arguments[3]; 
    } 

    if (!iKeyDelay || 0 > iKeyDelay) { 
     iKeyDelay = 500; 
    } 

    if (!sKeyEvent || !this[sKeyEvent]) { 
     sKeyEvent = 'keydown'; 
    } 

    // non-delayed event callback, should clear any timeouts, then 
    // call the original callback function 
    function fnExecCallback() { 
     clearTimeout(iTimeoutId); 
     fn.apply(this, arguments); 
    } 

    // delayed event callback, should call the non-delayed callback 
    // after a short interval 
    function fnDelayCallback() { 
     var that = this, 
      args = arguments; 
     clearTimeout(iTimeoutId); 
     iTimeoutId = setTimeout(function() { 
      fnExecCallback.apply(that, args); 
     }, iKeyDelay); 
    } 

    if (oEventData) { 
     this.change(oEventData, fnExecCallback); 
     this[sKeyEvent](oEventData, fnDelayCallback); 
    } 
    else { 
     this.change(fnExecCallback); 
     this[sKeyEvent](fnDelayCallback); 
    } 

    return this; 
    }; 

哪一种做到这一点,但它也会触发change,这意味着,如果我写的东西不动,后移动焦点说,5秒,然后当我终于,事件再次发生,它不应该。所以我只希望事件发生在keyup事件中。

如果任何人都可以解释如何使用该方法的工作,我怎么可能修改,以适应我的用例,这将是非常赞赏

回答

1

如果我理解您的使用情况,您可以使用此setTimeout()clearTimeout()

$(function() { 
 
    var timeOut = 0; 
 
    $("#test") 
 
     .keyup(function() { 
 
     // cancel looking, the user typed another character 
 
     clearTimeout(timeOut); 
 
     // set a timeout, when user doesn't type another key 
 
     // within half a second the function is called 
 
\t \t timeOut = setTimeout(function() { 
 
\t \t \t stopptedTyping(); 
 
\t \t }, 500); // change time as needed 
 
    }); 
 

 
}); 
 

 
function stopptedTyping(){ 
 
    alert('user stopped typing'); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="test"/>

+0

作品像我想的更简单,感谢您 – Tarlen 2015-02-08 10:05:09

+0

太客气 – DelightedD0D 2015-02-08 10:20:16