jQuery自动完成功能不适用于动态加载的元素 [英] jQuery autocomplete not working on dynamically loaded elements

查看:112
本文介绍了jQuery自动完成功能不适用于动态加载的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过ID为172的jQuery AJAX加载元素. 现在,我想在此元素上应用自动完成功能. 但是,以下代码不起作用.

I am loading an element through jQuery AJAX whose id is 172. Now i want to apply autocomplete on this element. However the following code is not working.

$(document).ready(function(){       
   $( "#172" ).autocomplete({
                minLength: 2,      
                source: function(request, response) {
                    var results = $.ui.autocomplete.filter(jsonCities, request.term);
                    response(results.slice(0, 10));
                },      
                focus: function( event, ui ) 
                {
                    $( "#172" ).val( ui.item.label );        
                    return false;      
                },      
                select: function( event, ui ) {
                    $( "#172" ).val( ui.item.label );        
                    $( "#172-id" ).val( ui.item.value );
                    return false;      
                }    
            });
});

我观察到这不适用于任何动态加载的元素.我想念什么?这是正确的方法还是其他方法?

I have observed that this doesnt work for any dynamically loaded element. What am i missing ? Is this the correct way or some other way is there?

推荐答案

类似的方法会起作用

$.ajax({
url:"..."
type:"...",
success:function(){
    //Add your #172 element and then use autocomplete on it
    $( "#172" ).autocomplete({}) 
}

});

由于调用自动完成功能时元素不在DOM上,因此没有任何自动完成行为,请在将元素添加到Ajax调用中的DOM后使用.

Since your element is not on the DOM when you call the autocomplete function nothing gets the autocomplete behavior, use if after you add the element to the DOM in your Ajax call.

这篇关于jQuery自动完成功能不适用于动态加载的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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