我有一张桌子,我试图根据表格单元格中的值存在来创建这样的东西。
获得的结果 - jsFiddle Result
<table width="100%" border="1" cellspacing="0" cellpadding="0" class="top-table-bg" id="mytable">
<tbody><tr>
<th style="width:200px"><br>First Row<br>Second Row<br>Third Row<br>Forth Row<br></th>
<th style="width:200px"><p>Heading1<br>
</p>
<p>First Row<br>
</p></th>
<th style="width:200px"><p>Heading2
<br>
</p>
<p>Second Row
<br>
Forth Row<br>
</p></th>
<th style="width:200px"><p>Heading3
<br>
</p>
<p>Second Row<br>
Third Row<br>
<br>
</p></th>
</tr>
<tr>
<td style="width:200px;text-align:center;">First Row</td>
<td style="width:200px;text-align:center;">20</td>
<td style="width:200px;text-align:center;"></td>
<td style="width:200px;text-align:center;"></td>
</tr>
<tr>
<td style="width:200px;text-align:center;">Second Row</td>
<td style="width:200px;text-align:center;"></td>
<td style="width:200px;text-align:center;">20</td>
<td style="width:200px;text-align:center;">20</td>
</tr>
<tr>
<td style="width:200px;text-align:center;">Third Row</td>
<td style="width:200px;text-align:center;"></td>
<td style="width:200px;text-align:center;"></td>
<td style="width:200px;text-align:center;">20</td>
</tr>
<tr>
<td style="width:200px;text-align:center;">Forth Row</td>
<td style="width:200px;text-align:center;"></td>
<td style="width:200px;text-align:center;">20</td>
<td style="width:200px;text-align:center;"></td>
</tr>
</tbody></table>
这就是我尝试过的,但它填充了所有值:(
我的尝试 - jsFiddle Try
$('#mytable>tbody>tr').each( function(){
if($(this).text() != '' ) {
$('th').append($(this).children('td').first().text() + "<br>");
}
});
让我知道我做错了什么..在jquery中开始......如果是一个基本的借口
答案 0 :(得分:2)
$('#mytable > tbody > tr').each(function() {
var $tr = $(this);
$tr.children("td").not(":nth-child(1)").each(function() {
if ($(this).text() != '') {
var index = $(this).index() + 1;
$("th")
.filter(":nth-child(" + index + ")")
.append("<br/>" + $tr.children("td:first").text());
}
});
})
#mytable th {
width:200px;
}
#mytable td {
text-align: center;
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table width="100%" border="1" cellspacing="0" cellpadding="0" class="top-table-bg" id="mytable">
<tr>
<th></th>
<th>Heading1</th>
<th>Heading2</th>
<th>Heading3</th>
</tr>
<tr>
<td>First Row</td>
<td>20</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Second Row</td>
<td></td>
<td>20</td>
<td>20</td>
</tr>
<tr>
<td>Third Row</td>
<td></td>
<td></td>
<td>20</td>
</tr>
<tr>
<td>Forth Row</td>
<td></td>
<td>20</td>
<td></td>
</tr>
</table>
我还用外部CSS替换了内联样式声明。