jQuery selector for every row except the first on

2019-07-03 05:10发布

问题:

I want to apply right alignment on the last cell of every table row, skipping the first table on the page and skipping the first row of every table.

I wrote the following:

$("table:gt(0) tr:gt(0) td:last-child").css("text-align", "right");
  1. The tables after the first are selected. GOOD.
  2. The last cell in each row is aligned right. GOOD.
  3. The first row in the first table in the result set is skipped. GOOD.
  4. Each first row in subsequent tables in the result set has the style applied. BAD.

I've tried passing a function to the "each" method on the wrapped set, but that isn't working. Any ideas?

回答1:

You were almost there.

$("table:gt(0)").find("tr:gt(0) td:last-child").css("text-align", "right");

otherwise, tr:gt(0) is always true because jquery is looking at each tr, not each tr in each table.



回答2:

try

$("table:gt(0) tr:not(:first-child) td:last-child").css("text-align", "right");

as the gt(0) only refers to the index in the jQuery object that you're building, not the table.



回答3:

what's wrong with using the DOM to select your tables, and using jQuery to apply your styles to the tables? too many lines of code?



回答4:

$("table:gt(0) tr").each(){
     if($(this).not(":first-child")){
           $(this).find("td:last-child").css("text-align","right");
     }
}

not the best way probably, but this is how I would do it.



回答5:

There is probably a better way, but one idea may be to add a class to the first row of each table that you do not want to have the style and filter those out with a not(.myclass).

Likewise add classes to the tables that you do want the styles to go to.