每行中第一个td的jQuery选择器

31

我有这些东西:

<table>
  <tr>
    <td>nonono</td> <!-- FIND THIS -->
    </td>foobar</td>
  </tr>
  <tr>
    <td>nonono2</td> <!-- FIND THIS -->
    </td>foobar2</td>
  </tr>
  <tr>
    <td>nonono3</td> <!-- FIND THIS -->
    </td>foobar2</td>
  </tr>
</table>

我已经尝试使用$('td:first')但没有成功;

期望返回:<td>nonono</td><td>nonon2</td><td>nonon3</td>

提前致谢!


1
文档中得知::first伪类相当于:eq(0)。它也可以写成:lt(1)。虽然它只匹配单个元素,但是:first-child可以匹配多个元素:每个父元素都会匹配一个。” - Felix Kling
7个回答

64

你应该使用:first-child而不是:first:

听起来像是你想要遍历它们。你可以使用.each()来实现这一点。

示例:

$('td:first-child').each(function() {
    console.log($(this).text());
});

结果:

nonono
nonono2
nonono3

或者,如果您不想迭代:

$('td:first-child').css('background', '#000');

JSFiddle演示


我会接受这个答案,因为另一种方法包含:first-child - Ragen Dazs

16

1
只需使用 first-child:first 不能单独使用的原因是它只会获取第一个元素,而不会获取更多。 - James Donnelly
1
这对我有用。当你正在寻找唯一选择时,我使用了:$(this).find("td:first") - Sander

10

你可以像这样做

$(function(){
  $("tr").find("td:eq(0)").css("color","red");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
  <tr>
    <td>col_1</td>
    <td>col_2</td>
  </tr>
</table>


3
var tablefirstcolumn=$("tr").find("td:first")
alert(tablefirstcolumn+"of Each row")

2

使用:

$("tr").find("td:first");

"

js fiddle - 这个例子在结尾处使用了 .text() 来显示它返回的元素。

或者,您也可以使用:

"
$("td:first-child");

.find() - jQuery API 文档

(Note: The original text appears to be in English, so this is just a rephrasing of the same text in Chinese.)

1
尝试
var children = null;
$('tr').each(function(){
    var td = $(this).children('td:first');
    if(children == null)
        children = td;
    else
        children.add(td);
});

// children should now hold all the first td elements

1

$('td:first-child')将返回您想要的元素的集合。

var text = $('td:first-child').map(function() {
  return $(this).html();
}).get();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接