將 HTML 表格轉換成陣列,用 JavaScript 如何操作?


使用 find()獲取標籤中的資料,並利用 push()將資料儲存到陣列中。我們將使用如下表格 -

<table id="details">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr><td>John</td><td>23</td>
<tr><td>David</td><td>26</td>
</tbody>
</table>

讓我們獲取 <td>中的資料並存儲到陣列中。以下為完整程式碼 -

示例

 線上演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style>
   .notShown {
      display: none;
   }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<table id="details">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr><td>John</td><td>23</td>
<tr><td>David</td><td>26</td>
</tbody>
</table>
<script>
   var convertedIntoArray = [];
   $("table#details tr").each(function() {
      var rowDataArray = [];
      var actualData = $(this).find('td');
      if (actualData.length > 0) {
         actualData.each(function() {
            rowDataArray.push($(this).text());
         });
         convertedIntoArray.push(rowDataArray);
      }
   });
   console.log(convertedIntoArray);
</script>
</body>
</html>

若要執行上述程式,請將檔案另存為“anyName.html(index.html)”,並右鍵單擊該檔案。在 VS 程式碼編輯器中選擇 “開啟檔案並啟用即時伺服器”。

輸出

這將生成以下輸出 -

更新於:01-Sep-2020

4K+ 次瀏覽

開啟您的 事業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.