【发布时间】:2021-05-11 05:46:43
【问题描述】:
我有一个表格,需要将<span> 附加到 td:first-child 单元格和 td:first-child 单元格。
问题:
-
在第一个 td 中已经存在
<span>。如果<span>已经存在,如何跳过附加? (如果 if 语句不知何故不起作用) -
我想知道为什么我的代码没有在 td:last-child 中附加
<span> -
请看第一列的第二行和第三行,插入文本在单元格中的文本之后(Jill 2 first-col,Jill 2 first-col)。如何将插入文本移到前面?
请帮帮我。谢谢!
$(document).ready(function() {
$('tr td:first-child').append('<span class="first-col"> first-col</span>');
if ($('tr td:first-child span').length) {
return false
}
$('tr td:last-child').append('<span class="second-col"> second-col</span>')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td><span class="first-col"> first-col</span>Jill</td>
<td>Smith</td>
</tr>
<tr>
<td>Jill 2</td>
<td>Smith 3</td>
</tr>
<tr>
<td>Jill 3</td>
<td>Smith 3</td>
</tr>
</table>
【问题讨论】:
-
td:first-child cell 和 td:first-child cell 这是什么意思?第二个
first-child应该是last-child吗? -
嗨 Barmar,如果我使用
nth-child(2)代替last-child,它可以工作。 -
if ($('tr td:first-child span').length)总是正确的......你期待什么 -
if ($('tr td:first-child span').length),我希望不再在该单元格中附加<span>,因为它已经有<span>