使用Ajax和按键优化搜索 [英] Optimised search using Ajax and keypress
问题描述
当用户在文本框中键入内容时,我想使用以下代码搜索数据库.下面的代码可以正常工作,但似乎效率低下,好像用户输入的速度非常快.我可能正在进行比必要更多的搜索.因此,如果用户输入"sailing",那么我正在搜索"sail","saili","sailin"和"sailing".
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".
我想看看是否有一种方法可以检测两次按键之间的任何特定时间,因此仅在用户停止键入500毫秒或类似的时间时进行搜索.
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.
是否有针对此类情况的最佳做法?
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();
});
}
}
推荐答案
您可以执行以下操作:
$('#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();
});
}
这是通过在#searchString
元素的keyup
上优于keypress
). jquery.com/data/"rel =" noreferrer> .data()
集合.每个keyup
都会清除该计时器,如果输入了密钥,则会立即搜索,如果没有在自动搜索之前设置另一个500ms
超时的话.
What this does is perform a search (on keyup
, better than keypress
for these situations) after 500ms
by storing a timer on the #searchString
element's .data()
collection. Every keyup
it clears that timer, and if the key was enter, searches immediately, if it wasn't sets a another 500ms
timeout before auto-searching.
这篇关于使用Ajax和按键优化搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!