jQuery 使用 Ajax 和按键优化搜索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3028704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:45:10  来源:igfitidea点击:

Optimised search using Ajax and keypress

jqueryajaxsearchkeypress

提问by leora

I have the following code that I want to use to search a database as a user is typing into a textbox. The code below works fine but it seems a little inefficient, as if a user is typing really fast. I am potentially doing many more searches than necessary. So if a user is typing in "sailing", I am searching on "sail", "saili", "sailin", and "sailing".

我有以下代码,当用户在文本框中键入内容时,我想用它来搜索数据库。下面的代码工作正常,但似乎有点低效,好像用户打字速度非常快。我可能会进行比必要更多的搜索。因此,如果用户输入“航行”,我将搜索“航行”、“航行”、“航行”和“航行”。

I wanted to see if there was a way to detect any particular time between keypresses so only search if user stops typing for 500 milliseconds or something like this.

我想看看是否有办法检测按键之间的任何特定时间,所以只搜索用户是否停止输入 500 毫秒或类似的东西。

Is there a best practice for something like this?

有这样的最佳实践吗?

$('#searchString').keypress(function(e) {

    if (e.keyCode == 13) {

        var url = '/Tracker/Search/' + $("#searchString").val();
        $.get(url, function(data) {
            $('div#results').html(data);
            $('#results').show();
        });
    }
    else {

        var existingString = $("#searchString").val();
        if (existingString.length > 2) {
            var url = '/Tracker/Search/' + existingString;
            $.get(url, function(data) {
                $('div#results').html(data);
                $('#results').show();
            });
        }
    }

回答by Nick Craver

You can do something like this:

你可以这样做:

$('#searchString').keyup(function(e) {
    clearTimeout($.data(this, 'timer'));
    if (e.keyCode == 13)
      search(true);
    else
      $(this).data('timer', setTimeout(search, 500));
});
function search(force) {
    var existingString = $("#searchString").val();
    if (!force && existingString.length < 3) return; //wasn't enter, not > 2 char
    $.get('/Tracker/Search/' + existingString, function(data) {
        $('div#results').html(data);
        $('#results').show();
    });
}

What this does is perform a search (on keyup, better than keypressfor these situations) after 500msby storing a timer on the #searchStringelement's .data()collection. Every keyupit clears that timer, and if the key was enter, searches immediately, if it wasn't sets a another 500mstimeout before auto-searching.

这样做是通过在元素的集合上存储计时器来执行搜索(在keyup,比keypress这些情况下更好)。每次它都会清除该计时器,如果输入了密钥,则立即搜索,如果没有,则在自动搜索之前设置另一个超时。500ms#searchString.data()keyup500ms

回答by johnwards

What I would do is each key press use a setTimeout function with the desired delay. So that function will fire after that timeout. Each key press then delete the timer and set a new one, with clearTimeout();

我会做的是每次按键都使用具有所需延迟的 setTimeout 函数。因此该函数将在超时后触发。每按一次键,然后删除计时器并设置一个新的计时器,使用 clearTimeout();

See here for some examples, scrolling past all the adverts.

有关一些示例,请参阅此处,滚动浏览所有广告。

http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

回答by Jerrin stephen

I just want to add some more points to the question. Throttling and debounce concepts are related to this topics.

我只是想为这个问题补充一些要点。节流和去抖动概念与此主题相关。

Throttling :It will make you to execute the function in a specified interval.

节流:它会让你在指定的时间间隔内执行函数。

Debounce :It will make you to execute the function when user has stopped typing.

Debounce :它会让您在用户停止输入时执行该功能。

You can achieve this two by setimeout , cleartimeout functions.Check this link will give you a clear walk-through of it.

您可以通过 settimeout 、 cleartimeout 函数实现这两个功能。检查此链接将为您提供清晰的演练。

LINK

关联