简体   繁体   English

当按住输入键时,防止按键方法被多次调用

[英]Prevent keypress method to be called multiple times when enter key held down

I am making a simple search bar using the HTML input tag: 我正在使用HTML输入标记创建一个简单的搜索栏:

<input type="text" id="search_bar" />

Then in jQuery I implement the keypress method to detect when the user hits the enter/return key: 然后在jQuery中我实现了keypress方法来检测用户何时点击enter / return键:

$('#search_bar').keypress(function(e) {
    if(e.keyCode == 13 && !e.shiftKey) { // enter/return
        e.preventDefault();
        //do stuff
    }
});

However, if the user decides the hold down the enter key, this method will be called multiple times. 但是,如果用户决定按住回车键,则会多次调用此方法。 I want to disable this behavior, ie keypress only called once when the user hits enter but not called again when the key is held down. 我想禁用此行为,即keypress仅在用户keypress enter时调用一次,但在按下该键时不再调用。 What is the best way to accomplish this? 完成此任务的最佳方法是什么?

Thanks. 谢谢。

Using onkeyup() will only detect when the key has been released. 使用onkeyup()只会检测密钥何时被释放。 This should solve your holding enter problem. 这应该解决你的持有输入问题。

$('#search_bar').keyup(function(e) {
    if(e.keyCode == 13 && !e.shiftKey) { // enter/return
        e.preventDefault();
        console.log("xx");
    }
});

Hold down enter -- xx is only logged on the release. 按住enter - xx仅记录在发行版上。

Fiddle: http://jsfiddle.net/veRkd/ 小提琴: http//jsfiddle.net/veRkd/

Try using keydown or keyup . 尝试使用keydownkeyup That will probably change the keycode value. 这可能会改变keycode值。

This is bit late to answer above question. 回答上述问题有点迟了。 But I would suggest to create a debounce function. 但我建议创建一个去抖功能。 The function will only fire once every fraction of a second instead of as quickly as it's triggered. 该功能每秒只会触发一次而不是触发它。 It surely helps to boost the performance incredibly. 这无疑有助于提升性能。

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

var apiRequestFunction = debounce(function() {
 //send an AJAX network request.
 //250 indicates the minimum time interval between the series of events being fired
}, 250);

$('#search_bar').keypress(function(e) {
        e.preventDefault();
        //do stuff
        //Function call to send an AJAX network request
        apiRequestFunction();
});

Reference blogpost by David Walsh 大卫沃尔什参考博文

Try using either the Keydown or Keyup event instead. 尝试使用KeydownKeyup事件。 They're only fired in the event of the key changing from one state to the other. 它们只有在钥匙从一个状态变为另一个状态时才被解雇。

You could use a timer since what you are experiencing is the behavior of keypress ( keyup and keydown could be used for counting the key presses but it will probably be rather tricky to track all edge cases on all browsers ). 你可以使用一个计时器,因为你遇到的是行为keypresskeyupkeydown可用于计算的按键,但它可能会是相当棘手的追踪所有在所有浏览器边缘的情况下 )。

$('#search_bar').keypress(function(e) {
    if(e.keyCode == 13 && !e.shiftKey) { // enter/return
        e.preventDefault();

        if (window.preventDuplicateKeyPresses)
            return;

        window.preventDuplicateKeyPresses = true;
        window.setTimeout(function() { window.preventDuplicateKeyPresses = false; }, 500 );

        //do stuff
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM