Как подсказывает Cruxst, для такого рода вещей существуют плагины, но, возможно, вы не хотите использовать плагин. Возможно, вы пытаетесь понять это для себя.
Вот фрагмент кода, который реализует очень простое автозаполнение. Это не плагин и довольно простой, но он имеет основные функции.
Ваш вопрос говорит о том, что функция, которая может вас заинтересовать, highlightResult
.
Под сценарием приведена разметка и требуемый стиль.
$(function() {
// OPTIONS
// length of time, in milliseconds, to wait after a keystroke before the search happens
// usually 250 ~ 400ms
var wait = 250;
// the minimum number of characters required to search on
var minChars = 3;
var queryScript = 'inc/ajax_search.php';
// cache our two main players for efficiency
var $input = $('#searchinput');
var $output = $('#searchresults' );
// to store the timeout
var delay = null;
$input.keypress( function( e ) {
switch( e.keyCode ) {
case 13: // return
e.preventDefault();
selectResult();
return;
case 38: // up
e.preventDefault();
highlightResult( -1 );
return;
case 40: // down
e.preventDefault();
highlightResult( 1 );
return;
//case ... there may be keys that you want to ignore like left and right
}
clearTimeout( delay );
delay = setTimeout( search, wait );
});
function search() {
var query = $.trim( $input.val() );
if( query && query.length >= minChars ) {
$output.load( queryScript, { searchinput: query } );
}
}
function highlightResult( n ) {
if( Math.abs(n) != 1 ) return;
var hilgt = $output.find( '.highlight' );
var newhilgt;
// if we don't have a highlighted element...
if( !hilgt.length ) {
if( n > 0 ) {
// highlight the first one
$output.find('li').eq(0).addClass('highlight');
// jq 1.4+
//$output.find('li').first().addClass('highlight');
} else {
// highlight the last one
$output.find('li').slice( -1 ).addClass('highlight');
// jq 1.4+
//$output.find('li').last().addClass('highlight');
}
}
if( n > 0 ) {
var newhilgt = hilgt.next();
} else {
var newhilgt = hilgt.prev();
}
if( newhilgt.length ) {
newhilgt.addClass('highlight');
hilgt.removeClass('highlight');
}
}
function selectResult() {
var sel = $output.find( '.highlight' );
if( sel.length ) {
// do something with the selected element
console.log( sel[0] );
}
}
// For completeness the functions below handle mouse stuff
$('#searchresults li').live( 'mouseover', function( e ) {
$(this).siblings('.highlight').removeClass('highlight');
$(this).addClass('highlight');
});
$('#searchresults li').live( 'click', function( e ) {
e.preventDefault();
selectResult();
})
});
Требования
<style type="text/css">
.highlight {
background: red;
}
</style>
<input type="text" id="searchinput"/>
<div id="searchresults"></div>
Возврат из вашего вызова ajax, предположительно что-то вроде
<ul>
<li>result 1</li>
<li>result 2</li>
<li>result 3</li>
...
</ul>