首页 > 解决方案 > 将 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);

标签: javascriptajax

解决方案


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


推荐阅读