3

我正在使用 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
    }
});

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

谢谢。

4

5 回答 5

4

使用onkeyup()只会检测到何时释放键。这应该可以解决您的控股输入问题。

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

按住回车--xx 只登录发布。

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

于 2013-04-22T19:31:47.723 回答
2

您可以使用计时器,因为您遇到的是keypresskeyup并且keydown可以用于计算按键次数,但跟踪所有浏览器上的所有边缘情况可能会相当棘手)。

$('#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
    }
});
于 2013-04-22T19:31:39.590 回答
2

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

于 2013-04-22T19:30:00.990 回答
2

回答上面的问题有点晚了。但我建议创建一个去抖动功能。该功能只会在每分之一秒内触发一次,而不是在触发时触发一次。它肯定有助于难以置信地提高性能。

// 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();
});

参考大卫沃尔什的博文

于 2019-03-19T10:19:30.683 回答
1

尝试改用KeydownKeyup事件。它们仅在密钥从一种状态更改为另一种状态时才会被触发。

于 2013-04-22T19:31:32.817 回答