防止按下enter键时多次调用按键方法

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

本文关键字:调用 方法 enter      更新时间:2023-09-26

我正在使用HTML输入标签制作一个简单的搜索栏:

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

然后在jQuery中,我实现了keypress方法来检测用户何时点击回车键:

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

但是,如果用户决定按住enter键,则将多次调用此方法。我想禁用此行为,即keypress仅在用户按enter键时调用一次,但在按住该键时不会再次调用。实现这一目标的最佳方式是什么?

谢谢。

使用onkeyup()将只检测键何时被释放。这应该可以解决你的等待输入问题。

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

按住enter键——xx只登录到该版本。

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

尝试使用keydownkeyup。这可能会改变keycode的值

你可以使用计时器,因为你正在经历的是keypress的行为(keyupkeydown可以用于计算按键次数,但在所有浏览器上跟踪所有边缘情况可能会相当棘手)。

$('#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
    }
});

现在回答上面的问题有点晚了。但我建议创建一个debounce函数。这个函数只会在几分之一秒内触发一次,而不是像触发时那么快。这无疑有助于不可思议地提高性能。

// 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();
});
作者:David Walsh

尝试使用Keydown或Keyup事件。它们只在键从一种状态改变到另一种状态时触发。