javascript jQuery - 如何选择表中所有行的最后一列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23940565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:51:31  来源:igfitidea点击:

jQuery - How to select last column of all rows in a table?

javascriptjqueryhtmljquery-selectors

提问by Alagappan Ramu

Assuming I have a HTML table as follows (with the appropriate tr, td tags):

假设我有一个如下的 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>

I'm trying to select all the c* rows to perform an action on them.

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

Using the $('td:last')selector just selects the last td tag, i.e., c4.

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

I tried $('tr > td:last')which didn't work. What would be the correct selector in this case?

我试过$('tr > td:last')哪个不起作用。在这种情况下,正确的选择器是什么?

回答by musicnothing

:lastis a jQuery selector, but it will only select the very last element of that type. You're most likely looking for :last-child.

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

Similarly, td:first-childwill get you the first cell, while :firstgets you the first element of that type.

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

Here's a Fiddlefor you to look at with all four examples.

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

回答by BoltClock

As mentioned, to select every tdthat is the last child of its parent tr, use :last-childinstead:

如上所述,选择每一个td是其父的最后一个孩子tr,使用:last-child,而不是:

$('td:last-child')

The reason why the :lastselector doesn't work is because it actually gives you the last element in the DOM that matches everything in the selector up to the point where it occurs:

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

  • $('td:last')returns the last tdelement
  • $('tr > td:last')returns the last tr > td
  • $('td:last')返回最后一个td元素
  • $('tr > td:last')返回最后一个 tr > td

Since every tdis tr > tdby necessity, there is no difference in these two selectors.

由于每个td都是tr > td必需的,因此这两个选择器没有区别。