在点击时动态添加输入元素

Dynamically adding input elements on onclick

本文关键字:添加 输入 元素 动态      更新时间:2023-09-26

我希望用户单击一个按钮并出现一个表单。但是无论他们按多少次这个按钮,都会出现一个表格。一个接一个地按照它们的创建顺序。我想在 JavaScript 中实现。

我不是专业人士,我在自学。只是想知道我是否说过:

<button id="new"><span class="glyphicon glyphicon-plus"> Add New Add-on</span></button>

可能吗?根据我所读到的内容,我想出了这个。但正如我所料,它不起作用。

<input type="button" id="new" name="new" value="Add New Add-On" class="btn" onclick="addFields()">
<div id="New_Form"/>
</div>
<script>
    function addFields(){
        var button = document.getElementById("new").value;
        var container = document.getElementById("New_Form");
        while (New_Form.hasChildNodes()) {
            New_Form.removeChild(New_Form.lastChild);
        }
        for (i=0;i<number;i++){
            New_Form.appendChild(document.createTextNode("new " + (i+1)));
            var input = document.createElement("input");
            input.type = "button";
            New_Form.appendChild(input);
            New_Form.appendChild(document.createElement("br"));
        }
    }  
</script> 

您的"唯一"错误是您尝试错误地访问div。此外,没有指定"数字",所以什么也没发生。

修复了这个问题并在此过程中评论了我/您的代码。请注意,我可能没有正确理解您的问题。您可以自由地进一步询问并指定您的需求。在我看来,到目前为止,这个脚本有点没用。但是继续学习!

<input type="button" id="new" name="new" value="Add New Add-On" class="btn" onclick="addFields()">
<div id="New_Form"/>
    <!--- Here goes the new form! -->
</div>
<script>
    function addFields(){
        // What did you want to accomplish here?
        //var button = document.getElementById("new").value;
        // You save the div with id "New_Form" into the variable container
        var container = document.getElementById("New_Form");
        // Now, why not use it then? :)
        while (container.hasChildNodes()) {
          // Removes all childs. NOTE: This will cause just one(!) form to appear in total!
            container.removeChild(container.lastChild);
        }
        // Number?? You need to specify some value here. I take 10 as an example.
        for (i=0; i < 10; i++) {
          // Again, use "container"
            container.appendChild(document.createTextNode("new " + (i+1)));
            var input = document.createElement("input");
            input.type = "button";
            container.appendChild(input);
            container.appendChild(document.createElement("br"));
        }
    }
</script>