我的自动补全射击太多次了



我在这里使用自动完成: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);

将执行ajax调用的部分拉到函数中,然后像这样"拆分"它:

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

这样你就可以在任何地方调用debouncedAjax,它现在调用ajax,它只会在500ms的间歇后进行一次调用。

我最终使用一个全局变量来存储调用Ajax函数的setTimeout(),每次keyup发生时,清除该变量并使用新的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'超时。

最新更新