使用 jQuery 在每一行中选择第一个 TD

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

Select first TD in every row w/ jQuery

jquery

提问by santa

How do I assign a style to every first cell of every row in a table?

如何为表格中每一行的每个第一个单元格分配样式?

$("#myTable tr td:first").addClass("black");

回答by Devin Burke

Use the :first-childpseudo class instead of :first.

使用:first-child伪类而不是:first.

$("#myTable tr td:first-child").addClass("black");

The :firstpseudo class actually selects the first element that was returned in your list. For example, $('div span:first')would return onlythe very first span under the first div that happened to be returned.

:first伪类实际上将会选择在您的列表中返回的第一个元素。例如,$('div span:first')返回碰巧返回的第一个 div 下的第一个跨度。

The :first-childpseudo class selects the first element under a particular parent, but returns as many elements as there are first children. For example, $('table tr td:first-child')returns the first cell of every single row.

:first-child伪类选择一特定父下的第一个元素,但返回一样多的元素有第一孩子。例如,$('table tr td:first-child')返回每一行的第一个单元格。

When you used :first, it was returning only the first cell of the first row that happened to be selected.

当您使用 时:first,它只返回碰巧被选中的第一行的第一个单元格。

For more information, consult the jQuery documentation:

有关更多信息,请参阅 jQuery 文档:

回答by nathan gonzalez

you were pretty close, i think all you need is :first-childinstead of :first, so something like this:

你非常接近,我认为你需要的只是:first-child而不是:first,所以是这样的:

$("#myTable tr td:first-child").addClass("black");

回答by bevacqua

$("#myTable tr").find("td:first").addClass("black");

回答by Teneff

like this:

像这样:

$("#myTable tr").each(function(){
    $(this).find('td:eq(0)').addClass("black");
});

回答by stefgosselin

Try:

尝试:

$("#myTable td:first-child").addClass("black");