我有两张这样的表:
Table # 1 Table # 2
| Minima | A | B | C | D | | Group | Minima | A | B | C | D |
--------------------------- ----------------------------------
| 1 | 0 | 0 | 0 | 1 | | |
--------------------------- ---------
| 15 | 1 | 1 | 1 | 1 | | |
--------------------------- ---------
| 3 | 0 | 0 | 1 | 1 | | |
--------------------------- ---------
| 6 | 0 | 1 | 1 | 0 | | |
--------------------------- ---------
我需要将表#1的所有行与表#2合并,我还需要创建与" 1"的数量相关的组。进入表#1的行。例如:Minima 3和6有2个数字" 1",这些应该在2组中。
表#2应如下所示:
Table #2
| Group | Minima | A | B | C | D |
----------------------------------
| 1 | 1 | 0 | 0 | 0 | 1 |
----------------------------------
| | 3 | 0 | 0 | 1 | 1 |
| 2 |-------------------------
| | 6 | 0 | 1 | 1 | 0 |
----------------------------------
| 4 | 15 | 1 | 1 | 1 | 1 |
----------------------------------
答案 0 :(得分:0)
请检查以下代码段
您可以做的是,从第一个表创建一个对象,根据1的数量对项目进行分组,然后使用此对象并在第二个表中创建行。
$(document).ready(function() {
var $table1 = $("#table1");
var rows = $table1.find("tbody tr");
var totalrows = rows.length;
var object = {};
rows.each(function(row) {
var newTr = jQuery("<tr/>")
var cols = $(this).find("td");
var colslength = cols.length;
var count = 0;
var i;
for (i = 1; i < colslength; i = i + 1) {
var $tdObject = $(cols[i]);
var tdText = parseInt($tdObject[0].innerText, 10);
if (tdText == 1) {
count++;
}
}
if (count > 0) {
if (!object[count]) {
object[count] = [];
}
object[count].push({
"Minimum": $(this).find("td:eq(0)")[0].innerText,
"A": $(this).find("td:eq(1)")[0].innerText,
"B": $(this).find("td:eq(2)")[0].innerText,
"C": $(this).find("td:eq(3)")[0].innerText,
"D": $(this).find("td:eq(4)")[0].innerText
});
}
});
AppendRows(object);
});
function AppendRows(object) {
Object.keys(object).forEach(function(item) {
createRows(object[item], item);
});
}
function createRows(arr, group) {
var $table2 = $("#group2");
var len = arr.length;
var idx = 0;
while (idx < len) {
var row = jQuery("<tr/>");
if (idx == 0) {
var td = $("<td></td>");
td.html(group);
row.append(td);
if (len > 1) {
td.attr('rowspan', len)
}
}
Object.keys(arr[idx]).forEach(function(obj) {
var td = $("<td></td>");
td.html(arr[idx][obj]);
row.append(td);
});
$table2.append(row);
idx++;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table1" border="1">
<thead>
<tr>
<th>Minimum</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</thead>
<tbody>
<tr>
<td>
1
</td>
<td>
0
</td>
<td>
0
</td>
<td>
0
</td>
<td>
1
</td>
</tr>
<tr>
<td>15</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>6</td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>0</td>
</tr>
</tbody>
</table>
<table id="group2" border="1">
<thead>
<tr>
<th>Group</th>
<th>Minima</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</thead>
</table>
希望这有帮助