jQuery jquery选择每组除最后一个之外的所有元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2401109/
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-08-26 13:26:08  来源:igfitidea点击:

jquery selecting all elements except the last per group

jqueryjquery-selectors

提问by Anthony

I have a table that looks like:

我有一张看起来像的表:

<table>
   <tr>
      <td>one</td><td>two</td><td>three</td><td>last</td>
   </tr>
   <tr>
      <td>blue</td><td>red</td><td>green</td><td>last</td>
   </tr>
   <tr>
      <td>Monday</td><td>Tuesday</td><td>Wednesday</td><td>last</td>
   </tr>
</table>

What I want is a jquery selector that will choose all but the last tdof each table row. I tried:

我想要的是一个 jquery 选择器,它将选择td每个表行的最后一行。我试过:

$("tr td:not(:last)").css("background-color","red");
  //changing color just as a test...

But instead of all cells but the last on each row being changed, all cells but the very last one in the table are selected. Similarly, if I change it to:

但是,除了每行最后一个单元格之外的所有单元格都被更改,而是选择了表格中除最后一个单元格之外的所有单元格。同样,如果我将其更改为:

$("tr td:last").css("background-color","red");

the only one that changes is the very last cell. How do I choose the last (or not last) of each row?

唯一改变的是最后一个单元格。如何选择每一行的最后一个(或不是最后一个)?

回答by Nick Craver

Use this:

用这个:

$('tr td:not(:last-child)').css('background-color', 'red');

It's saying each <td>that's not the last in that particular <tr>

它说每一个<td>都不是那个特定的最后一个<tr>

回答by Alex Bagnolini

$('tr').find('td:not(:last)').css('background-color', 'red');

Translates to: for each element in $('tr')selector, do a find()for all tds that are not last.
New result is about tds now, so you can apply .css()as wanted.

转换为:对于$('tr')选择器中的每个元素,find()对所有td不在最后的 s执行 a 。
新的结果现在大约td是 s,因此您可以.css()根据需要申请。