我必须要按钮: add ,在那里我想向我的按钮中添加s(它们来自一个选定的数字)和Reset,在那里要删除这些元素。我知道我需要在删除DOM元素之后克隆它们,但是如何实现它们。我对JS比较陌生。或者,我可以切换到一个复选框与此解决方案:带有复选框和克隆任何帮助赞赏- thks。
<!DOCTYPE html>
<html lang="en">
<head>
<title>reprex jquery</title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// what´s the value of the integer input?
var no = 10;
let i = 1;
$("#btn-add").click(function() {
while (i <= no) {
$("#tbl tbody").append("<tr><td><input></input></td><td><textarea></textarea></td></tr>");
$("#tbl input")[i-1].setAttribute("name", "s" + i);
$("#tbl input")[i-1].setAttribute("value", i);
$("#tbl textarea")[i-1].setAttribute("name", "c" + i);
++i;
}
});
});
$(document).ready(function() {
$("#btn-remove").click(function() {
$("#tbl tr:gt(0)").remove();
});
});
</script>
</head>
<body>
<div>
<button class="btn" id="btn-add" type="button">Add</button>
<button class="btn" id="btn-remove" type="button">Reset</button>
</div>
<table id="tbl">
<thead>
<tr>
<th>col1</th>
<th>col2</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
发布于 2022-06-17 22:22:09
您可以通过检查i
的状态来添加回行。因为它是全局定义的,所以当您继续使用它时,值会发生变化。请考虑以下几点。
$(function() {
var no = 10;
var i = 1;
$("#btn-add").click(function() {
if (i > 1) {
i = 1;
}
while (i <= no) {
$("#tbl tbody").append("<tr><td><input></input></td><td><textarea></textarea></td></tr>");
$("#tbl input")[i - 1].setAttribute("name", "s" + i);
$("#tbl input")[i - 1].setAttribute("value", i);
$("#tbl textarea")[i - 1].setAttribute("name", "c" + i);
++i;
}
});
$("#btn-remove").click(function() {
$("#tbl tbody tr").remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>
<button class="btn" id="btn-add" type="button">Add</button>
<button class="btn" id="btn-remove" type="button">Reset</button>
</div>
<table id="tbl">
<thead>
<tr>
<th>col1</th>
<th>col2</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
在这里,您可以看到i
在您的while
中发生了更改。当用户单击"Add“按钮时,您可能需要重置它。
https://stackoverflow.com/questions/72665261
复制相似问题