简体   繁体   English

删除动态创建的输入

[英]Deleting dynamically created inputs

So is there an easy way to get the last node so I could simply delete inputs from the last one? 那么,有没有一种简单的方法来获取最后一个节点,以便我可以简单地从最后一个节点中删除输入? deleteinput() function. deleteinput()函数。


<script>

    var form = document.getElementById("form");


    function newinput(){    
        var input = document.createElement("input");
        input.type = "text";
        form.appendChild(input);
    }
    function deleteinput(){

        form.removeChild();

    }
</script>

You should add your input s some id as well so you can delete them by providing id as an argument to your deleteinput() function. 您还应该添加input的一些id ,以便可以通过将id作为您的deleteinput()函数的参数来删除它们。

Your function will look like this 您的功能将如下所示

function deleteinput(name) {
    var input = document.getElementByName(name);
    form.removeChild(input);
}

Also newinput() will change accordingly: 同样, newinput()也会相应更改:

function newinput(name) {
    var input = document.createEleement("input");
    input.type = "text";
    input.name = name;
    form.appendChild(input);
}

You can also create some global integer and generate name of input automatically by some string + incremented value of your global variable - this way you don't need to pass name argument to newinput() function. 您还可以创建一些全局整数,并通过一些字符串+全局变量的递增值自动生成输入名称-这样,您无需将name参数传递给newinput()函数。

I am not sure that this will 100% work, I did not test it. 我不确定这是否会100%有效,但我没有进行测试。 Maybe you will need to tweak it little bit but the main logic should be correct. 也许您需要进行一些微调,但主要逻辑应该是正确的。

You can use the lastChild property to get the last child, and the previousSibling to step through them until you get to an input 您可以使用lastChild属性获取最后一个孩子,并使用previousSibling逐步浏览它们,直到获得input为止

function deleteinput() {
    for (var child = form.lastChild; child.nodeName.toLowerCase() != 'input'; child = child.previousSibling) {
    }
    if (child) {
        form.deleteChild(child);
    }
}

Yes you can get and remove the last element this way. 是的,您可以通过这种方式获取和删除最后一个元素。

var ele = document.getElementById("parent element Id").lastChild;
ele.remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM