高效率的AutoSuggest使用jQuery? [英] Efficient AutoSuggest with jQuery?

查看:117
本文介绍了高效率的AutoSuggest使用jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个jQuery插件的AutoSuggest,灵感来自于苹果的聚光灯下。

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

下面是一般code:

$(document).ready(function() { 
$('#q').bind('keyup', function() {

    if( $(this).val().length == 0) {
        // Hide the q-suggestions box
        $('#q-suggestions').fadeOut();
    } else {
        // Show the AJAX Spinner
        $("#q").css("background-image","url(/images/ajax-loader.gif)");

        $.ajax({
            url: '/search/spotlight/',
            data: {"q": $(this).val()},
            success: function(data) {
                $('#q-suggestions').fadeIn(); // Show the q-suggestions box
                $('#q-suggestions').html(data); // Fill the q-suggestions box

                // Hide the AJAX Spinner
                $("#q").css("background-image","url(/images/icon-search.gif)");

            }
        });
    }
});

这个问题我想解决井放;优雅的,不杀断绝。眼下code每次输入一个密钥,不等待你基本上完成打字时上面打服务器。什么是解决这个问题的最好方法是什么? 答:杀previous AJAX请求? B.某些类型的AJAX缓存? C.添加某种类型的延迟只提交阿贾克斯()时,该人已停止输入300毫秒左右?

The issue I want to solve well & elegantly, is not killing the sever. Right now the code above hits the server every time you type a key and does not wait for you to essentially finish typing. What's the best way to solve this? A. Kill previous AJAX request? B. Some type of AJAX caching? C. Adding some type of delay to only submit .AJAX() when the person has stopped typing for 300ms or so?

推荐答案

请尝试使用本Alman的油门和放大器;防抖动插件

让你延时的事情,直到用户完成。

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

有关如何使用它检查了他的具有防抖动的例子为例一个pretend自动完成

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

您code将基本成为

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');
}

您会注意到,我删除了你的背景图像的CSS和addClass / removeClass移除取而代之。更容易在css文件管理CSS的东西。

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.

这篇关于高效率的AutoSuggest使用jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆