Jquery选择器没有选择值

时间:2015-07-10 20:04:55

标签: jquery

以下是我的表格,我正在尝试从表格中选择元素

<table id="DetailsGridViewDiv_Header" style="border: 1px solid;">
    <tbody>
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
            <th>D</th>
            <th>E</th>
            <th>F</th>
            <th>G</th>
            <th>H</th>
        </tr>
    </tbody>
</table>

这就是我尝试从表中提取值的方法:

alert($("#DetailsGridViewDiv_Header > th:nth-child(3)").text());

它不会返回任何字母

3 个答案:

答案 0 :(得分:2)

问题是因为您使用了直接后代选择器(>)而th不是#DetailsGridViewDiv_Header的直接后代。删除该运算符,它将正常工作:

alert($("#DetailsGridViewDiv_Header th:nth-child(3)").text());

如果要保留后代选择器,则需要按顺序跟随后代元素:

alert($("#DetailsGridViewDiv_Header > tbody > tr > th:nth-child(3)").text());

答案 1 :(得分:1)

th不是ID为DetailsGridViewDiv_Header的表的直接后代,所以应该是:

$("#DetailsGridViewDiv_Header th:nth-child(3)").text()

答案 2 :(得分:1)

当你在jQuery中选择它时会返回一个数组,所以使用eq()函数来选择jQuery对象会更有意义(谢谢,Rory!):

var $thArray = $("#DetailsGridViewDiv_Header").find("th");
alert($thArray.eq(2).text());