jQuery check on wordchange rather than "change" trigger
I have a input that the user types a search parameter into, at the moment i have it on keyup to do a POST ajax request to a PHP script that returns search results. however its firing off 50 billion (not literally) post requests in about 10 seconds (as the user types) 开发者_StackOverflow中文版which slows the whole experience down. Can i use jQuery to detect a "wordup" rather than "keyup" by detecting the use of the space bar?
Does this make sense?
I'm adding this as a separate answer, because it's entirely different to my first answer.
$('#yourinput').keyup(function(){
var input = this,
timer = $.data(this, 'timer'),
lastrequest = $.data(this, 'lastrequest');
if (timer) { // if there is a keyup timeout still pending, cancel it
clearTimeout(timer);
$.data(this, 'timer', 0);
}
if (lastrequest) { // if there is an AJAX request still running, abort it
lastrequest.abort();
$.data(this, 'lastrequest', false);
}
timer = setTimeout(function(){
lastrequest = $.post({ // or whatever your AJAX call is...
url: 'yourfile',
data: { search: input.value },
success: function(response){
lastrequest = false;
// handle response here
}
});
$.data(input, 'lastrequest', lastrequest);
}, 500);
$.data(this, 'timer', timer);
});
$('#yourinput').keyup(function(e) {
if (e.which == 32) { // space key pressed
// do your AJAX here
}
});
See event.which
for more information about this feature.
You certainly could; you detect the keyup events locally and check them for space.
But you'll get a lot more leverage if you can contrive to get all the search results that match a prefix and send them down to the javascript in a data structure. Have a look at "digital search trees" (also known as "tries") for details.
You could use something like a delay for when the user has stopped typing for a specific period of time?
Perhaps something like this? You could add the additional function to trigger a space bar press as well. (This was used just for a Google-Style insta-search, so it may / may not help).
$('#Search').keyup(function (event)
{
delay(function(){
var textboxValue = $('#Search').val();
if( textboxValue.length >= 2)
{
//Perform search
}
});
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
精彩评论