将 JavaScript 函数应用于动态创建的元素



我有一个自动完成功能,它适用于已经创建的id="field10"输入字段。但是,当我动态创建新的输入字段时,该函数不适用于它们。我什至在创建字段之前指定了输入字段名称。我已经检查了创建的字段 ID 是否正确,我做错了什么?下面是用于生成新输入字段的脚本。

//Add Input Fields
$(document).ready(function() {
var max_fields = 10; //Maximum allowed input fields 
var wrapper    = $(".array_wrap"); //Input fields wrapper
var add_button = $(".add_fields"); //Add button class or ID
var x = 1; //Initial input field is set to 1
//When user click on add input button
$(add_button).click(function(e){
e.preventDefault();
//Check maximum allowed input fields
if(x < max_fields){ 
x++; //input field increment
//add input field
var inputA = document.createElement('a');
$(inputA).attr("href", "javascript:void(0);");
$(inputA).attr("class","remove_field")
inputA.innerText ="Remove";
var inputName = document.createElement('input');
$(inputName).attr('id','field10' + x);
$(inputName).attr('type','text');
$(inputName).attr('name','input_array_name[]');
$(inputName).attr('placeholder','Subject');
$(inputName).appendTo($(wrapper));
$(inputA).appendTo($(wrapper));
}
});
//
These are the values I have passed to the function...
autocomplete(document.getElementById("field10"), countries);
autocomplete(document.getElementById("field101"), countries);
autocomplete(document.getElementById("field102"), countries);
autocomplete(document.getElementById("field103"), countries);
autocomplete(document.getElementById("field104"), countries);
autocomplete(document.getElementById("field105"), countries);
autocomplete(document.getElementById("field106"), countries);

您确定这些是正确的 ID 吗? 否则,我认为使用类而不是 Id 是值得的,因为您必须循环具有该类名的元素数组,因此更容易动态。

最新更新