如何在 append() 中使用 jQuery each() 方法
How to use jQuery each() method within an append()
我有一个向 table 添加新行的函数。我还创建了一个函数,用于获取具有相似 ID 的文本输入的值。
我想要做的是将收集的值附加到 table,每列一个。最后一列将包含删除行 link。我不知道如何在 append 方法中进行迭代(也许是 each 方法?)。这是我的代码。
添加行函数
$('.addrow').click(function(){
$('.datatable > tbody:last-child')
.append($('<tr>')
.append($('<td>')
.append($('<a>')
.attr('id', 'deleterow')
.attr('href','#')
.text('delete')
)
)
);
});
删除行函数
$('.datatable').on('click', '.deleterow', function(){
$(this).closest('tr').remove();
});
获取输入值函数
$("input[class='textinput']").map(function(){return $(this).val();}).get();
代码结构应该是这样的:
$("#addrow").click(function() {
var new_row = $("<tr>");
$("input.textinput").each(function() {
new_row.append($("<td>", {
text: $(this).val();
});
});
new_row.append($("<td>").append($("<a>", {
"class": "deleterow",
"href": "#",
"text": "delete"
});
$(".datatable tbody").append(new_row);
});
循环遍历要用于填充 table 列的数据,并在该循环中追加每个单元格。
你可以这样使用它。在这种情况下,对于具有 class .copy
的 "each" 元素,代码将在回调函数中 运行。
$(document).ready(function () {
$( ".copy" ).each(function() {
$("#target").append($(this).html());
});
});
我有一个向 table 添加新行的函数。我还创建了一个函数,用于获取具有相似 ID 的文本输入的值。
我想要做的是将收集的值附加到 table,每列一个。最后一列将包含删除行 link。我不知道如何在 append 方法中进行迭代(也许是 each 方法?)。这是我的代码。
添加行函数
$('.addrow').click(function(){
$('.datatable > tbody:last-child')
.append($('<tr>')
.append($('<td>')
.append($('<a>')
.attr('id', 'deleterow')
.attr('href','#')
.text('delete')
)
)
);
});
删除行函数
$('.datatable').on('click', '.deleterow', function(){
$(this).closest('tr').remove();
});
获取输入值函数
$("input[class='textinput']").map(function(){return $(this).val();}).get();
代码结构应该是这样的:
$("#addrow").click(function() {
var new_row = $("<tr>");
$("input.textinput").each(function() {
new_row.append($("<td>", {
text: $(this).val();
});
});
new_row.append($("<td>").append($("<a>", {
"class": "deleterow",
"href": "#",
"text": "delete"
});
$(".datatable tbody").append(new_row);
});
循环遍历要用于填充 table 列的数据,并在该循环中追加每个单元格。
你可以这样使用它。在这种情况下,对于具有 class .copy
的 "each" 元素,代码将在回调函数中 运行。
$(document).ready(function () {
$( ".copy" ).each(function() {
$("#target").append($(this).html());
});
});