我们正在研究使用 jquery 动态插入元素的自动完成(之前对静态元素进行过自动完成)。下面是插入一个自动完成添加元素的 html 源代码(同一页面上可能插入多个元素)。插入元素的 id 在插入之前是未知的。 id 因元素而异:
<input type="text" size="50" placeholder="Enter keyword" name="requisition[material_items_attributes][1414037215952][item_name_autocomplete]" id="requisition_material_items_attributes_1414037215952_item_name_autocomplete" data-autocomplete-source="/whs/items/autocomplete" class="string required span5">
这是自动完成的js代码:
$(function() {
$("[id^='requisition_material_items_attributes_'][id$='_item_name_autocomplete']").each(function (){
return $(this).autocomplete({
minLength: 1,
source: $(this).data('autocomplete-source'),
select: function(event, ui) {
$(this).val(ui.item.value);
}
});
});
});
当在文本框中输入关键字时item_name_autocomplete
, 什么都没发生。我们发现autocomplete的js代码没有执行,没有匹配到id。什么可能导致不匹配?是因为动态元素需要在匹配之前重新加载(不确定这里如何使用 .on 。还是有其他方法可以重新加载)?
setTimeout解决了这个问题:
setTimeout(function(){
$("[id^='requisition_material_items_attributes_'][id$='_item_name_autocomplete']").each(function (){
$(this).autocomplete({
minLength: 1,
source: $(this).data('autocomplete-source'),
select: function(event, ui) {
$(this).val(ui.item.value);
}
});
});
}, 5000);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)