html 克隆div标签,同时使用JavaScript更改其元素的id属性(多个元素)

qyswt5oh  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(181)
  • 我希望克隆一个div,同时也改变了提到的div内的元素的ID *
    我克隆div时使用的代码是
<!DOCTYPE html>
<html lang="en">
<body>
  <form>
      <div class="dynamic-field" id="dynamic-field-1">
          <div>
      <label for="name" class="hidden-md">Name</label>
      <input type="text" id="name-1" class="form-control" name="field[]" />
    </div>
    <div>
      <label for="age" class="hidden-md">Age</label>
      <input type="text" id="age-1" class="form-control" name="field[]" />
    </div>
      </div>
      <div>
        <button type="button" id="add-button">
          Add
        </button>
      </div>
  </form>
  <script src='https://code.jquery.com/jquery-3.3.1.slim.min.js'></script>
  <script>
    $(document).ready(function () {
      var buttonAdd = $("#add-button");
      var className = ".dynamic-field";
      var count = 0;

      function totalFields() {
        return $(className).length;
      }

      function addNewField() {
        count = totalFields() + 1;
        field = $("#dynamic-field-1").clone();
        field.attr("id", "dynamic-field-" + count);
        field.find("input").val("");
        $(className + ":last").after($(field));
      }

      buttonAdd.click(function () {
        addNewField();
      });

    });
  </script>
</body>

</html>

使用的代码可以克隆div并以增量方式更改其id。问题在于更改元素输入id和标签的名称
克隆的div元素的id需要类似于例如field-1,field 2,... etc

预期结果为..

<form>
<div class="dynamic-field" id="dynamic-field-">
    <div>
        <label for="name" class="hidden-md">Name</label>
        <input type="text" id="name-1" class="form-control" name="field[]" />
    </div>
    <div>
        <label for="age" class="hidden-md">Age</label>
        <input type="text" id="age-1" class="form-control" name="field[]" />
    </div>
</div>
<div class="dynamic-field" id="dynamic-field-2">
    <div>
        <label for="name" class="hidden-md">Name</label>
        <input type="text" id="name-2" class="form-control" name="field[]" />
    </div>
    <div>
        <label for="age" class="hidden-md">Age</label>
        <input type="text" id="age-2" class="form-control" name="field[]" />
    </div>
</div>
<div>
    <button type="button" id="add-button">
        Add
    </button>
</div>
  • 我如何通过改变现有代码而不使用完全不同的方法来实现 *
wmtdaxz3

wmtdaxz31#

使用Jquery attr

field.find("input").attr("id","field-" + count);
field.find("label").attr("for","field-" + count);

相关问题