javascript - 将 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 是值得的,因为您必须在具有该类名的元素数组上循环,它更容易成为动态的。
推荐阅读
- javascript - sinon库的fake,spy,stub和mock之间的区别(sinon fake vs spy vs stub vs mock)
- optimization - 任何语言都可以“深度”组合或简化功能吗?
- python - (安装gym环境) UnicodeDecodeError: 'utf-8' codec can't decode byte
- c - 如何将值传递给另一个函数(通过引用/值调用)?(C)
- omnet++ - OMNET++中peekAtFront的作用是什么
- http - 在 Camel REST DSL 中构建 HTTP 响应时避免超时
- apache-spark - Pyspark:如何计算RDD中每个等距离间隔的数量
- python - Pandas iterrows 无法按预期处理数据框
- android - 如何使用货币代码将数字格式化为货币 (ISO 4217)
- c# - C# | HTML | 找不到此本地主机页面