28

I have this stuff:

<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>

I have tried with $('td:first') with no luck;

Expected return: <td>nonono</td>, <td>nonon2</td> and <td>nonon3</td>

Thanks in advance!

4

7 回答 7

60

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

听起来你想遍历它们。您可以使用.each().

例子:

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

结果:

nonono
nonono2
nonono3

或者,如果您不想迭代:

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

JSFiddle 演示

于 2013-05-21T10:49:38.060 回答
15

试试这个选择器 -

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

演示--> http://jsfiddle.net/66HbV/

或者

$("tr td:first-child")

演示--> http://jsfiddle.net/66HbV/1/

</td>foobar</td>应该<td>foobar</td>

于 2013-05-21T10:46:07.363 回答
7

你可以这样做

$(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>

于 2018-08-16T08:26:16.137 回答
3
var tablefirstcolumn=$("tr").find("td:first")
alert(tablefirstcolumn+"of Each row")
于 2017-12-01T12:52:44.193 回答
2

利用:

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

js fiddle - 这个例子.text()最后表明它正在返回元素。

或者,您可以使用:

$("td:first-child");

.find()- jQuery API 文档

于 2013-05-21T10:54:22.263 回答
1

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

var text = $('td:first-child').map(function() {
  return $(this).html();
}).get();
于 2013-05-21T10:52:08.347 回答
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
于 2013-05-21T10:51:11.480 回答