开发者

Selecting second cell of a row using jQuery

I have the following HTML table

<table>
<tr class="trSelected">
<td>One</td>
<td>two</td>
</tr>
</table>

I just want to get the text in the second column (ie,'two')

I tried

$('.trSelected td').eq(2).val(开发者_如何学JAVA)

but it returs an empty string How it is possible through jQuery?


You should use the following construction:

$('.trSelected td').eq(1).text()

or

$('.trSelected td:eq(1)').text()

eq selector uses zero-based index. Also you have to use text method, not val.


List Indices start from 0, not from 1.

You are trying to select column 3, which does not exist. Also, the .val() method is only used for getting and setting form fields, not normal html elements. Use .text() instead!

$('.trSelected td').eq(1).text()

might work.


Use the nth-child selector to get the second cell

$(".trSelected td:nth-child(2)").val()


First for all, eq()'s argument is a 0-based index, so to get the second element, you'd need to call eq(1).

Secondly, the val() method is used to retrieve the value from inputs, you're dealing with td elements, not inputs.

$('.trSelected td').eq(1).text()

will do what you're expecting.


You could use the nth-child selector or you should use eq(1). Also, you should use .text() or .html() instead of .val()

An example in jsFiddle: http://jsfiddle.net/heTyW/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜