2015-07-10 170 views
1

以下是我的表,我想從表中選擇元素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()); 

它不返回任何字母

+1

大聲笑,@Rory,那是什麼在第一編輯:d – nicael

+1

@尼卡爾該死的,我以爲我會逃避它:DI有我在剪貼板中編輯過的另一個問題,並不小心將它粘貼在 –

回答

1

th不與ID DetailsGridViewDiv_Header表的直系後裔,所以應該是:

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

的問題是,因爲你使用的嫡系選擇(>)和th不是#DetailsGridViewDiv_Header的直系後裔。刪除操作,它會很好地工作:

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

如果你想保持後代選擇,您將需要遵循後代元素依次是:

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

當你在jQuery的它選擇的東西返回一個數組,所以它可能更有意義,使用EQ()函數來選擇jQuery對象(感謝,羅裏!):

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

請注意,這會給你一個錯誤 - 你在DOMElement上調用text(),而不是在jQuery對象上調用。 –

+0

不,find()返回一個jQuery對象。 – SeanKendle

+2

沒錯,但通過索引('$ thArray [2]')訪問它會返回一個DOMElement。 –