gpt4 book ai didi

javascript - 如何使用 jquery 更新表头

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:19:28 26 4
gpt4 key购买 nike

我有一个表格,我正在尝试根据表格单元格中存在的值创建类似的东西。

要获得的结果 - 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 入门..如果是基本的请原谅

最佳答案

$('#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 替换了内联样式声明。

关于javascript - 如何使用 jquery 更新表头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14934415/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com