簡體   English   中英

使用jquery讀取HTML表的第一列值

[英]Read the first column values of a HTML table with jquery

我有一張桌子:

<table id="ItemsTable" >​
    <tbody>
   <tr>
     <th>
       Number
     </th>
     <th>
       Number2
     </th>
    </tr>
  <tr>
    <td>32174711</td>     <td>32174714</td>
  </tr>
  <tr>
    <td>32174712</td>     <td>32174713</td>
  </tr>
</tbody>
</table>

我需要將值32174711和32174712以及列號的每個其他值放入數組或列表中,我使用的是jquery 1.8.2。

var arr = [];
$("#ItemsTable tr").each(function(){
    arr.push($(this).find("td:first").text()); //put elements into array
});

請參閱此鏈接以獲取演示:

http://jsfiddle.net/CbCNQ/

你可以使用map方法:

var arr = $('#ItemsTable tr').find('td:first').map(function(){
     return $(this).text()
}).get()

http://jsfiddle.net/QsaU2/

來自jQuery map()文檔:

描述:通過函數傳遞當前匹配集中的每個元素,生成一個包含返回值的新jQuery對象。 由於返回值是一個jQuery包裝的數組,因此get()返回的對象與基本數組一起使用是很常見的。

// iterate over each row
$("#ItemsTable tbody tr").each(function(i) {
    // find the first td in the row
    var value = $(this).find("td:first").text();
    // display the value in console
    console.log(value);
});

http://jsfiddle.net/8aKuc/

從你擁有的,你可以使用第一個孩子

var td_content = $('#ItemsTable tr td:first-child').text()
// loop the value into an array or list

http://jsfiddle.net/Shmiddty/zAChf/

var items = $.map($("#ItemsTable td:first-child"), function(ele){
    return $(ele).text();
});

console.log(items);​

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM