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

标签 javascript html function button input

我创建了一个小型网站,我想在其中动态添加/删除输入字段。我已经编写了添加它们的代码,它运行完美,但删除输入字段有点困难。

下面是我的文档在创建输入后的样子。现在使用“删除按钮”,我尝试删除最后一个 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>

最佳答案

我可能会通过分组而不是使用换行符来简化和抽象出 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>

关于javascript - 如何使用 JavaScript 动态删除换行符和文本输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67989922/

相关文章:

java - 使用 Html 或 JavaScript 在 Java 中滚动图像?

html - 网站未在手机上使用 Bootstrap 居中

c++ - if 语句中的函数名以一种奇怪的方式转换

arrays - 如何在 fortran 中调用数组值函数?

C 在 main 中调用打印函数

javascript - DIV 调节 - 检查 DIV 中是否存在 IMG

javascript - 在街景中显示 InfoWindow(使用 InfoBubble)

javascript - 未提交表单,单击后禁用提交按钮时未加载页面

javascript - 打开弹出窗口时在 Javascript 中使用媒体查询

javascript - Phonegap应用程序通过wifi发送数据