开发者

Select the first field from jQuery autocomplete function automatically

When I mouseover a field in my autocomplete list it adds a class named selected. I want it to do that by default on the first line as soon as you start typing. How would i select the first 开发者_开发问答element in that list and change it's class?

I'm using this now but it flickers a lot.

$('.name').eq(0).addClass('selected');


You may want to use jQuery's toggleClass() and first() for that.

$('.name').first().toggleClass('selected');


I'm betting the flicker is caused by calling it on every keyup event. You need to 'debounce' the function call.

Debouncing functions with jQuery:

http://benalman.com/projects/jquery-throttle-debounce-plugin/

Like this:

$('input:text').keyup( $.debounce( 250, function() {
  // run autocomplete routine / ajax call here
  $('.name').eq(0).addClass('selected');
}) );

That requires a jQuery plugin of course, so if you'd rather have a minimal-footprint version, use John Hann's pure-Javascript version:

Debouncing functions with pure Javascript and less code:

Or if you don't want to use another plugin, debouncing is as easy as:

var debounce = function (func, threshold, execAsap) {

  var timeout;

  return function debounced () {
    var obj = this, args = arguments;
    function delayed () {
        if (!execAsap)
            func.apply(obj, args);
        timeout = null; 
    };

    if (timeout)
        clearTimeout(timeout);
    else if (execAsap)
        func.apply(obj, args);

    timeout = setTimeout(delayed, threshold || 100); 
  };
};

Usage:

$('input:text').keyup( debounce(function() {
  // run autocomplete routine / ajax call here
  $('.name').eq(0).addClass('selected');
}), 250, false );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜