问题描述
如何为表格中每行的每个第一个单元格分配样式?
How do I assign a style to every first cell of every row in a table?
$("#myTable tr td:first").addClass("black");
推荐答案
使用:first-child
伪类代替:first
.
$("#myTable tr td:first-child").addClass("black");
:first
伪类实际上选择了列表中返回的第一个元素.例如,$('div span:first')
只会在碰巧返回的第一个div下仅返回仅.
The :first
pseudo class actually selects the first element that was returned in your list. For example, $('div span:first')
would return only the very first span under the first div that happened to be returned.
:first-child
伪类选择特定父级下的第一个元素,但返回的数量与第一个子级一样多.例如,$('table tr td:first-child')
返回每行的第一个单元格.
The :first-child
pseudo 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
时,它仅返回碰巧被选中的第一行的第一个单元格.
When you used :first
, it was returning only the first cell of the first row that happened to be selected.
有关更多信息,请查阅jQuery文档:
For more information, consult the jQuery documentation:
- http://api.jquery.com/first-selector/
- http://api.jquery.com/first-child-selector/
这篇关于使用jQuery在每一行中选择第一个TD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!