jQuery:重新实现< t to<去除它们后
我必须使用按钮:添加,我想将s添加到我的(它们来自选定的编号)和 reset 想要删除这些元素的地方。我知道我需要在删除它们后克隆元素,但是如何实现它。我是JS的新手。另外,我可以在此处使用此解决方案切换到复选框:带有复选框和克隆 。
<!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>
I have to buttons: Add, there I want to add s to my (they come from a selected number) and Reset where want to remove those elements. I know I need to clone DOM elements after removing them, but how do I implement it. I´m relatively new to JS. Alternatively I can switch to a checkbox with this solution here: with checkbox and cloning Any help appreciated - 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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过检查
i
的状态来添加行。由于它在全球范围内得到了更大的定义,因此随着您继续使用它,价值会改变。考虑以下内容。在这里,您可以看到<代码> i 在时在
中更改。当用户单击“添加”按钮时,您可能需要将其重置。
You can add back your rows by checking the status of
i
. Since it's defined more globally, as you continue to use it, the value changes. Consider the following.Here you can see that
i
is changed in yourwhile
. You may need to reset it when the User clicks on "Add" button.