我的自动完成功能被解雇了很多次

时间:2011-04-24 08:38:59

标签: javascript jquery autocomplete

我在这里使用自动填充功能:http://blog.idealmind.com.br/geral/simple-autocomplete-jquery-plugin/

它有两个问题:

1)第一次输入文本框时它不起作用 - 这不是一个大问题,因为你真的不想匹配一个字母 2)更刺激的是它发射的次数太多了。

我的javascript在这里:

<script type="text/javascript">
  function nameAutocomplete(field){
  alert($(field).val());
$("#name").simpleAutoComplete(
        'Ajax.action',
        {   'input': $(field).val(),
            '_eventName': 'getObjectsByAjax'
        },
        function(data){
        alert("we're in business");
        }
    );
}  
</script>

HTML看起来像这样:

 <input type="text" name="name" id="name" size="45" class="medium-text" onkeyup="nameAutocomplete(this);"/>

这是进行Ajax调用的插件(下面)的一部分(工作正常):

            $.get(page, 
                {   'input': thisElement.val(),
                    '_eventName': 'getObjectsByAjax'
                },
                    function(res) 
                {
                $('div.' + classAC).remove();
                $("#autocomplete_tooltip").remove();
                var r="";
                var respObject=eval(res);
                r+="<ul>";
                for(var i in respObject)
                    {
                        r+='<li id="autocomplete_'+respObject[i].id+'"><table cellspacing=0 width="100%"><tr><td class="icon" width="20" uri="'+respObject[i].uri+'"><a href="/sempedia/Resource.action?id='+respObject[i].id+'" ><img src="images/green-file.png"></a></td><td class="caption">'+respObject[i].name+"</td></tr></table></li>";
                    }
                r+="</ul>";
                autoCompleteList = $('<div>').addClass(classAC).html(r);

我在这里打印了整个插件代码:

 (function($){
$.fn.extend(
{
    simpleAutoComplete: function( page, options, callback ) {
        if(typeof(page) == "undefined" ) {
            alert("simpleAutoComplete: Você deve especificar a página que processará a consulta.");
        }

        var classAC = 'autocomplete';
        var selClass = 'sel';
        var attrCB = 'rel';
        var thisElement = $(this);

        $(":not(div." + classAC + ")").click(function(){
            $("div." + classAC).remove();
            $("#autocomplete_tooltip").remove();
        });

        thisElement.attr("autocomplete","off");

        thisElement.keyup(function( ev )
        {   var getOptions = { input: thisElement.val() }

            if( typeof(options) == "object" )
            {
                classAC = typeof( options.autoCompleteClassName ) != "undefined" ? options.autoCompleteClassName : classAC;
                selClass = typeof( options.selectedClassName ) != "undefined" ? options.selectedClassName : selClass;

                attrCB = typeof( options.attrCallBack ) != "undefined" ? options.attrCallBack : attrCB;
                if( typeof( options.identifier ) == "string" )
                getOptions.identifier = options.identifier;

                if( typeof( options.extraParamFromInput ) != "undefined" )
                getOptions.extraParam = $( options.extraParamFromInput ).val();
            }

            kc = ( ( typeof( ev.charCode ) == 'undefined' || ev.charCode === 0 ) ? ev.keyCode : ev.charCode );
            key = String.fromCharCode(kc);

            console.log(kc, key, ev );

            if (kc == 27)
            {
                $('div.' + classAC).remove();
                $("#autocomplete_tooltip").remove();
            }
            if (kc == 13)
            {
                $('div.' + classAC + ' li.' + selClass).find(".caption").trigger('click');
            }
            if (key.match(/[a-zA-Z0-9_\- ]/) || kc == 8 || kc == 46)
            {
                $.get(page, 
                    {   'input': thisElement.val(),
                        '_eventName': 'getObjectsByAjax'
                    },
                        function(res) 
                    {
                    $('div.' + classAC).remove();
                    $("#autocomplete_tooltip").remove();
                    var r="";
                    var respObject=eval(res);
                    r+="<ul>";
                    for(var i in respObject)
                        {
                            r+='<li id="autocomplete_'+respObject[i].id+'"><table cellspacing=0 width="100%"><tr><td class="icon" width="20" uri="'+respObject[i].uri+'"><a href="/sempedia/Resource.action?id='+respObject[i].id+'" ><img src="images/green-file.png"></a></td><td class="caption">'+respObject[i].name+"</td></tr></table></li>";
                        }
                    r+="</ul>";
                    autoCompleteList = $('<div>').addClass(classAC).html(r);
                    if (r != '')
                    {
                        autoCompleteList.insertAfter(thisElement);

                        var position = thisElement.position();
                        var height = thisElement.height();
                        var width = thisElement.width();

                        $('div.' + classAC).css({
                            'top': ( height + position.top + 6 ) + 'px',
                            'left': ( position.left )+'px',
                            'margin': '0px'
                        });

                        $('div.' + classAC + ' ul').css({
                            'margin-left': '0px'
                        });

                        $('div.' + classAC + ' li').each(function( n, el )
                        {
                            el = $(el);
                            el.mouseenter(function(){
                                $('div.' + classAC + ' li.' + selClass).removeClass(selClass);
                                $(this).addClass(selClass);
                            });
                            el.find(".caption").click(function()
                            {
                                thisElement.attr('value', el.text());

                                if( typeof( callback ) == "function" )
                                    callback( el.attr(attrCB).split('_') );

                                $('div.' + classAC).remove();
                                thisElement.focus();
                            });

                            el.hover(function(e) {
                                urlText=$("<div>").attr("id","autocomplete_tooltip").addClass("tooltip").html($(this).find("td").attr("uri"));

                                urlText.css({
                                    position:"absolute",
                                    top:(e.pageY+20)+"px",
                                    left:(e.pageX+20)+"px"
                                    });

                                $("body").append(urlText);
                            },function() {
                                $("#autocomplete_tooltip").remove();
                            });


                        }); 
                    }
                });
            }
            if (kc == 38 || kc == 40){
                if ($('div.' + classAC + ' li.' + selClass).length == 0)
                {
                    if (kc == 38)
                    {
                        $($('div.' + classAC + ' li')[$('div.' + classAC + ' li').length - 1]).addClass(selClass);
                    } else {
                        $($('div.' + classAC + ' li')[0]).addClass(selClass);
                    }
                }
                else
                {
                    sel = false;
                    $('div.' + classAC + ' li').each(function(n, el)
                    {
                        el = $(el);
                        if ( !sel && el.hasClass(selClass) )
                        {
                        el.removeClass(selClass);
                        $($('div.' + classAC + ' li')[(kc == 38 ? (n - 1) : (n + 1))]).addClass(selClass);
                        sel = true;
                        }
                    });
                }
            }
            if (thisElement.val() == '') {
                $('div.' + classAC).remove();
                $("#autocomplete_tooltip").remove();
            }
        });
    }
});
  })(jQuery);

2 个答案:

答案 0 :(得分:2)

将执行ajax调用的部分拉入函数,然后将"debounce"像这样:

var timeout = thisElement.data('timeout');

function debouncedAjax() {
  if (timeout) {
    clearTimeout(timeout);
  }
  timeout = setTimeout(ajax, 500);
  thisElement.data('timeout', timeout);
}

通过这种方式,您可以在现在调用debouncedAjax的任何地方调用ajax,并且只会在暂停500毫秒后执行一次调用。调整超时以尝试。

答案 1 :(得分:0)

我最终使用全局变量来存储setTimeout()并调用Ajax函数,并且每次键盘发生时都清除此变量并使用新的Ajax调用重置它,如下所示:

$(document).ready(function () {
    // Define the global variable
    $.go = null;
    // Element keyup
    $("#YourElementId").keyup(function() {
        // Clear the global variable with the previous Ajax
        clearTimeout($.go);
        // Set the variable with the current Ajax call
        $.go = setTimeout(function() {
            FunctionThatCallsTheAjax();
        },1000);
    });
});
function FunctionThatCallsTheAjax(){
    // Ajax Stuff Here
}

您可以调整'1000'超时。 它对我很好。

相关问题