我们正在使用jquery动态插入的元素进行自动完成(以前对静态元素做过自动完成)。下面是插入的一个自动完成添加元素的html源代码(可能有多个元素插入在同一个页面上)。插入元素的id在插入之前是未知的。ids因元素而异:
<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的文本框中时,什么都不会发生。我们发现,用于自动完成的js代码没有被执行,并且没有与id匹配。是什么导致了不匹配?这是因为动态元素需要在匹配之前重新加载(这里不确定如何使用.on )。或者还有其他方法来重新加载)?
发布于 2014-10-25 05:31:08
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);发布于 2014-10-25 06:14:44
您可以将onload代码放入函数中,因此,当您创建新内容时,再次启动函数onload .
$(document).ready(function() {
function returnAccess(){
//all your code when the page load
//all the code you need to run like events or something else...
}
function createContent(){
//code that create content
//then you run returnAccess() again
returnAccess();
}
returnAccess();
});因此,当您创建新内容时,再次触发returnAccess() ..。即使您可以将函数createContent放入返回访问,如果新内容也执行了创建内容.
https://stackoverflow.com/questions/26529225
复制相似问题