Efficient AutoSuggest with jQuery?

前端 未结 4 1618
北荒
北荒 2021-02-01 11:15

I\'m working to build a jQuery AutoSuggest plugin, inspired by Apple\'s spotlight.

Here is the general code:

$(document).ready(function() { 
$(\'#q\').         


        
4条回答
  •  生来不讨喜
    2021-02-01 11:46

    Try using Ben Alman's Throttle & Debounce plugin

    Lets you "delay" things till the user is done.

    For an example on how to use it check out his example of debouncing with a pretend autocomplete

    Your code would basically become

    var qinput = $('#q').bind('keyup', $.debounce( 250, function() {
    
        if( $(this).val().length == 0) {
            // Hide the q-suggestions box
            $('#q-suggestions').fadeOut();
        } else {
            // Show the AJAX Spinner
            qinput.addClass('loading');
    
            $.ajax({
                url: '/search/spotlight/',
                data: {"q": $(this).val()},
                success: function(data) {
                    $('#q-suggestions')
                        .fadeIn() // Show the q-suggestions box
                        .html(data); // Fill the q-suggestions box
    
                    // Hide the AJAX Spinner
                   qinput.removeClass('loading').addClass('search');
                }
            });
        }
    }));
    

    CSS

    .loading{
        background: url('/images/ajax-loader.gif');
    }
    .search{
        background: url('/images/icon-search.gif');
    }
    

    You will note that I removed your background-image css and replaced them with addClass/removeClass. Much easier to manage css stuff in css files.

提交回复
热议问题