我在二维数组上有一个嵌套的 $.each 来生成一个我无法弄清楚的表。由于某种原因它会重复表格单元格。我已经尽可能地简化了它,但仍然出现错误。
HTML:
<table id="mytable" class="table table-bordered table-striped"></table>
JavaScript:
var header_array = ["one", "two", "three", "four", "five"];
$("#mytable").append("<thead><tr></tr></thead>");
$.each(header_array, function(index, value) {
$("#mytable thead tr").append("<th>" + value + "</th>")
});
var data_array = [ ["one", "two", "three", "four", "five"],
["one", "two", "three", "four", "five"],
["one", "two", "three", "four", "five"]
];
$("#mytable").append("<tbody></tbody>");
$.each( data_array, function( index1, value1 ) {
$("#mytable tbody").append("<tr></tr>");
$.each( value1, function( index2, value2 ) {
$("#mytable tbody tr").append("<td>"+ value2 + "</td>")
});
});
出于某种原因,最后一部分:
$.each( value1, function( index2, value2 ) {
$("#mytable tbody tr").append("<td>"+ value2 + "</td>")
});
在第一次迭代中追加所有 data_array,然后追加 data_array 中的 2/3 子数组,然后追加 data_array 的一个子数组,而不仅仅是 value1。有谁知道为什么吗?
谢谢
最佳答案
这是您的原始代码:
$("#mytable").append("<tbody></tbody>");
$.each( data_array, function( index1, value1 ) {
$("#mytabletbody").append("<tr></tr>");
$.each( value1, function( index2, value2 ) {
$("#mytabletbody tr").append("<td>"+ value2 + "</td>")
});
});
此代码片段的第一行将一个新的 tbody 添加到 #mytable 元素内部的末尾。接下来,您将循环遍历二维数组的行(这很好)。对于每一行,您都将一个新的 tr 添加到 DOM 中的 #mytabletbody 元素。这是一个问题,因为代码中没有任何内容表明 DOM 中实际上存在 id 为“mytabletbody”的元素。您可以将其更改为“#mytable > tbody”,这将找到 #mytable 元素并在其直接子元素中搜索所有 tbody。但是,您仍然会遇到问题,因为下一行代码会循环遍历表当前行中的每个元素。对于行中的每个元素,它执行以下行:
$("#mytabletbody tr").append("<td>"+ value2 + "</td>")
现在,问题在于 $("#mytabletbody tr") 正在查找 #mytabletbody 内的所有 tr,这不仅会选择当前的 tr,还会选择任何已创建的 tr。我建议更改代码以如下方式工作:
// Create variables that we will use to store JQuery objects
var $tbody, $tr, $td;
// Make a new <tbody>
$tbody = $("<tbody></tbody>");
// Loop through rows of array
$.each( data_array, function( index1, value1 ) {
// Make a new <tr>
$tr = $("<tr></tr>");
// Loop through elements of current row
$.each( value1, function( index2, value2 ) {
// Make a new <td> and set contents
$td = $("<td></td>").html(value2);
// Append current <td> to current <tr>
$tr.append($td);
});
// Append current <tr> to <tbody>
$tbody.append($tr);
});
// Append <tbody> to <table>
$("#mytable").append($tbody);
在这里,我们在将 DOM 元素附加到 DOM 之前创建并填充它们。这样,当我们最终将预先创建和预先填充的 $tbody 附加到 #mytable 时,我们只需对 DOM 进行一次重新渲染。
关于javascript - 二维数组上的每个嵌套 Jquery 错误地重复表格单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28906718/