- 我希望克隆一个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>
- 我如何通过改变现有代码而不使用完全不同的方法来实现 *
1条答案
按热度按时间wmtdaxz31#
使用Jquery
attr
: