【问题标题】:JQuery Autocomplete on Ajax loaded contentAjax 加载内容上的 JQuery 自动完成
【发布时间】:2011-09-28 10:12:57
【问题描述】:

我想在使用 Ajax 加载的输入框上使用 JQuery 的自动完成插件:

我尝试使用以下代码来实现这一点,但是它仅在用户单击两次输入时才有效:

$(document).ready(function() {
    $('#auto').live('keydown', function(){
        $(this).autocomplete(
          "/autocomplete",
          {
            delay:10,
            minChars:2,
            matchSubset:1,
            matchContains:1,
            cacheLength:10,
            onItemSelect:selectItem,
            onFindValue:selectItem,
            formatItem:formatItem,
            autoFill:true
        });
    });
});

能否告诉我我的代码是否有问题?

谢谢,

【问题讨论】:

  • 为什么不试试 $("#auto").focus(function(){...}); ?

标签: jquery ajax binding autocomplete listener


【解决方案1】:

有问题的解决方案有一个问题。 它只在第二个字符之后执行自动完成,因为第一个字符不能用于自动完成查询,因此这是触发keydown并执行自动完成控件注册的那个。

以下代码附加到所有(匹配的)现有和新创建的 (Ajax) 元素的 focus 事件,并在您单击或 Tab 进入输入后执行 autocomplete() 注册:

$(document).delegate(":input[data-autocomplete]", "focus", function() {
    $(this).autocomplete({
        source: $(this).attr("data-autocomplete"),
    });
})

在这个例子中,选择器查找所有具有"data-autocomplete"属性的元素,相同的属性被用作源url:

<input id="1" data-autocomplete="++URL++">

重要提示: 根据版本,您可以首先使用live()delegate()on() 函数。这三个的签名略有不同,但很容易弄清楚它们是如何相互映射的:

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

【讨论】:

    【解决方案2】:
    $('#auto').live('keydown', function(){
    
        $( "#auto" ).autocomplete({
        source: data,
        minLength: 3
        });
    

    });

    以上对我有用...

    【讨论】:

    • 这仅适用于minLength>1。原因是第一个字符不能用于自动完成查询,因为这是触发keydown并为autocomplete执行控件注册的字符。
    【解决方案3】:

    我不确定,但我认为您示例中的 live() 函数将绑定 keydown 事件,以便它仅在您触发后应用自动完成。尝试跳过 live() 并仅使用自动完成功能:

    $(document).ready(function() {
        $('#auto').autocomplete(
           "/autocomplete",
           {
                delay:10,
                minChars:2,
                matchSubset:1,
                matchContains:1,
                cacheLength:10,
                onItemSelect:selectItem,
                onFindValue:selectItem,
                formatItem:formatItem,
                autoFill:true
           }
        );
    });
    

    【讨论】:

    • 这行不通,因为 OP 正在尝试将小部件应用于通过 AJAX 加载的内容。
    • 是的,我认为只有在输入字段与页面一起加载时才会起作用。
    • 同意@mnml 这是常见的附加方式,在 ajax 内容的情况下不起作用 - 这正是这个问题的主题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 2013-08-06
    相关资源
    最近更新 更多