【问题标题】:jQuery - How to select last column of all rows in a table?jQuery - 如何选择表中所有行的最后一列?
【发布时间】:2014-07-19 09:14:49
【问题描述】:

假设我有一个如下的 HTML 表格(带有适当的 tr、td 标签):

a1 | b1 | c1
a2 | b2 | c2
a3 | b3 | c3
a4 | b4 | c4

<table border="1">
<tr>
    <td>a1</td>
    <td>b1</td>
    <td>c1</td>
</tr>
<tr>
    <td>a2</td>
    <td>b2</td>
    <td>c2</td>
</tr>
<tr>
    <td>a3</td>
    <td>b3</td>
    <td>c3</td>
</tr>
<tr>
    <td>a4</td>
    <td>b4</td>
    <td>c4</td>
</tr>
</table>

我正在尝试选择所有 c* 行来对它们执行操作。

使用$('td:last') 选择器只选择最后一个 td 标记,即 c4。

我尝试了$('tr &gt; td:last'),但没有成功。在这种情况下,正确的选择器是什么?

【问题讨论】:

  • @AlexMorrise 这行得通!谢谢。您可以将其添加为答案吗?
  • 试试 $('tr td:last-child')
  • 刚刚添加它作为答案。

标签: javascript jquery html jquery-selectors


【解决方案1】:

如前所述,要选择作为其父 tr 的最后一个孩子的每个 td,请改用 :last-child

$('td:last-child')

:last 选择器不起作用的原因是因为它实际上为您提供了 DOM 中与选择器中的所有内容匹配的最后一个元素,直到它出现:

  • $('td:last') 返回最后一个 td 元素
  • $('tr &gt; td:last') 返回最后一个 tr &gt; td

由于每个td 必然是tr &gt; td,所以这两个选择器没有区别。

【讨论】:

    【解决方案2】:

    :last 是一个 jQuery 选择器,但它只会选择 该类型的最后一个元素。您最有可能在寻找:last-child

    同样,td:first-child 会为您提供第一个单元格,而:first 将为您提供该类型的第一个元素。

    这里有一个Fiddle 供您查看所有四个示例。

    【讨论】:

    • 它不能用作直接的 CSS 选择器,但它应该用作 jQuery 选择器。如果您正在为 IE8 或更低版本进行开发,最好这样做:$('td:last-child').addClass('last-child') 并通过 $('td.last-child') 引用它。
    • 您似乎将:last:last-of-type 混淆了。 :last 不是 CSS 选择器,您给出的描述完美地描述了 :last-of-type,并不能完全描述 :last 的实际工作原理。
    • 抱歉,我编辑了我的答案。我的意思是,:last 是一个有效的 jQuery 选择器。
    • @BoltClock, :last-of-type 也不总是这样工作。 Google Chrome 中的这个示例jsfiddle.net/DFXJ3/2 隐藏了最后一个子元素,而不是td 类型的最后一个子元素。
    • @Alex Morrise:啊,这就是事情变得更加令人困惑的地方——它在其父级中隐藏了td 类型的最后一个元素,所以它基本上是特定类型的:last-child,这是预期的行为.
    猜你喜欢
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多