27

i'm trying to create a search where you input text into a textfield and onkeyup it will fire a function off that will send the value of the field to a page and return the results to the div container. The problem i'm having is that when someone is typing, there is a horrible lag going on. I think what's going on is that it's trying to search each letter typed in and does each request. How do i make it so that if i type into the box, wait 1/2 a second (500), if nothing is typed in, then do the ajax search,but if in that time frame another letter comes up, don't even bother with the ajax request. I've been busting my head on this and can't figure it out. All help is appreciated!

// fired off on keyup
function findMember(s) {
    if(s.length>=3)
        $('#searchResults').load('/search.asp?s='+s);
}
4

3 回答 3

54

这将做的是清除每次按下的超时,所以如果 1/2 秒还没有过去,函数将不会被执行,然后再次设置一个 500 毫秒的计时器。就是这样,不需要加载一个大库..

let timeoutID = null;

function findMember(str) {
  console.log('search: ' + str)
}

$('#target').keyup(function(e) {
  clearTimeout(timeoutID);
  const value = e.target.value
  timeoutID = setTimeout(() => findMember(value), 500)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" id="target" placeholder="Type something" />

于 2012-04-25T15:19:38.173 回答
6

jquery ui 自动完成具有此功能。

http://jqueryui.com/demos/autocomplete/

如果你不想使用 jquery ui,那么看看他们的源代码。

于 2012-04-25T15:18:11.867 回答
2
function myFunction(inputText) {
                debugger;
                var inputText = document.myForm.textBox.value;

                var words = new Array();
                var suggestions = "Always", "azulejo", "to", "change", "an", "azo", "compound", "third"];
                if (inputText != "") {
                    for (var i = 0; i < suggestions.length; ++i) {
                        var j = -1;
                        var correct = 1;
                        while (correct == 1 && ++j < inputText.length) {
                            if (suggestions[i].toUpperCase().charAt(j) != inputText.toUpperCase().charAt(j)) correct = 0;
                        }
                        if (correct == 1) words[words.length] = suggestions[i];
                        document.getElementById("span1").innerHTML = words;

                    }
                }

                else {
                    document.getElementById("span1").innerHTML = "";

                }

<p id="demo"></p>
    <form name="myForm">
         <input type="text" name="textBox" onkeyup="myFunction()"/>
         <span id="span1"></span>
    </form>
于 2015-08-26T13:26:05.703 回答