在jQuery中使用clone方法可以复制表行,并为控件创建新的唯一ID。下面是具体的步骤:
var clonedRow = $(".table-row").clone();
var counter = 1;
clonedRow.find("input").each(function() {
var originalId = $(this).attr("id");
var newId = originalId + counter;
$(this).attr("id", newId);
});
上述代码中,假设需要复制的行中包含input元素,通过遍历每个input元素,获取原始的ID,然后将计数器的值附加到原始ID上,最后使用attr方法设置新的ID。
clonedRow.insertAfter(".table-row:last");
上述代码中,假设需要将复制的行插入到表格中的最后一行之后。
完整的示例代码如下:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<table>
<tr class="table-row">
<td><input type="text" id="input1"></td>
<td><input type="text" id="input2"></td>
</tr>
</table>
<button id="cloneButton">Clone Row</button>
<script>
$(document).ready(function() {
$("#cloneButton").click(function() {
var clonedRow = $(".table-row").clone();
var counter = 1;
clonedRow.find("input").each(function() {
var originalId = $(this).attr("id");
var newId = originalId + counter;
$(this).attr("id", newId);
});
clonedRow.insertAfter(".table-row:last");
});
});
</script>
</body>
</html>
这个示例代码中,点击"Clone Row"按钮会复制表格中的行,并为复制的行中的控件创建新的唯一ID,然后将复制的行插入到表格中的最后一行之后。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)和腾讯云对象存储(COS)。
没有搜到相关的文章