2017-05-30 176 views
0

這看起來應該是直截了當的,但我不能得到它的工作。如何獲得<th>標籤的文本

HTML

<table id="mytable"> 
    <thead> 
     <tr> 
     <th>Head1</th> 
     <th>Head2</th> 
     </tr> 
    </thead> 
    <tbody> 
     ..body stuff.. 
    </tbody> 
</table> 

JS

$("#mytable > thead > tr > th").each(function() { 
    console.log($(this).text(); 
}) 

控制檯顯示每個文本值 「未定義」。

+1

你檢查在控制檯中發生錯誤?你只是缺少''''。 '的console.log($(本)的.text());' – dariru

回答

0

保持眼睛上的控制檯..你有一個語法錯誤($(this).text()應該是($(this).text())您忘記)

$("#mytable > thead > tr > th").each(function() { 
 
    console.log($(this).text()); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="mytable"> 
 
    <thead> 
 
     <tr> 
 
     <th>Head1</th> 
 
     <th>Head2</th> 
 
     </tr> 
 
    </thead> 
 
    <tbody> 
 
     ..body stuff.. 
 
    </tbody> 
 
</table>

重要:一定要包括jQuery的