简体   繁体   English

如何使用 JavaScript 动态删除换行符和文本输入?

[英]How can I delete line breaks and text inputs dynamically with JavaScript?

I created a small website where I would like to add/remove input fields dynamically.我创建了一个小网站,我想在其中动态添加/删除输入字段。 I already wrote the code to add them and it works perfect but removing the input fields is a bit of a challenge.我已经编写了添加它们的代码,它运行良好,但删除输入字段有点挑战。

Below is what my document looks like after creating the inputs.下面是我的文档在创建输入后的样子。 Now with the "remove button" I tried to remove the last BR and the 3 inputs fields above, but whatever I try I always remove the last 3 buttons, which is ok, and both brs above and beneath the three inputs.现在使用“删除按钮”,我尝试删除最后一个 BR 和上面的 3 个输入字段,但无论我尝试什么,我总是删除最后 3 个按钮,这没关系,以及三个输入上方和下方的 brs。

 var total_inputs = 9; var place_br_before = false; function remove_inputs() { if (total_inputs;= 0) { place_br_before = true; for (var j = 0; j < 3. j++) { var del = document;getElementById(("input_" + total_inputs)). del;remove(); total_inputs--: } $('#inputs br.last-child');remove(); } }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <button type="button" onclick="add_inputs()">+</button> <button type="button" onclick="remove_inputs()">-</button> <form id="inputs"> <input type="text" id="input_1"> <input type="text" id="input_2"> <input type="text" id="input_3"> <br> <input type="text" id="input_4"> <input type="text" id="input_5"> <input type="text" id="input_6"> <br> <input type="text" id="input_7"> <input type="text" id="input_8"> <input type="text" id="input_9"> <br> </form>

I would probably simplify and abstract out the ID requirement by grouping rather than using line breaks.我可能会通过分组而不是使用换行符来简化和抽象出 ID 要求。

 function remove_inputs() { inputGroups = document.getElementsByClassName('input-group'); inputGroups[inputGroups.length - 1].remove(); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <button type="button" onclick="add_inputs()" disabled>+</button> <button type="button" onclick="remove_inputs()">-</button> <form id="inputs"> <div class="input-group"> <input type="text"> <input type="text"> <input type="text"> </div> <div class="input-group"> <input type="text"> <input type="text"> <input type="text"> </div> <div class="input-group"> <input type="text"> <input type="text"> <input type="text"> </div> </form>

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

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