首页 > 解决方案 > 如何使用 jquery 将信息推送到多向数组中?

问题描述

我有如下采购表。

项目 数量 费率 Amnt
ABC 2 100 200
DEF 1 300 300

单击保存按钮时,我希望将此信息存储在多向数组中,例如
Array[0][0] = ABC
Array[0][1] = 2
Array[0][2] = 100
Array[0][ 3] = 100
Array[1][0] = DEF
Array[1][0] = 1
Array[1][1] = 300
Array[1][3] = 300


请帮助我如何分配这样的使用jQuery。

标签: jqueryarrays

解决方案


最终的 JS 代码取决于你的表格的 HTML 结构,但数据抓取逻辑可能如下:

// Add click event listener
$('#saveBtn').on("click", function() {
  const tbody = $('#myTable tbody');
  const resultData = [];
  
  // Loop through each tr
  $('tr', tbody).each(function(rowIndex) {
    const trElement = $(this);
    const rowData = []
    
    // Loop through each td
    $('td', trElement).each(function(colIndex) {
      const tdElement = $(this);
      rowData[colIndex] = tdElement.text();
    });
    
    resultData[rowIndex] = rowData;
  });
  
  console.log(resultData);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Possible HTML code of the table:</p>

<table id="myTable">
    <thead>
        <tr>
            <th>Item</th>
            <th>QTY</th>
            <th>Rate</th>
            <th>Amnt</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>ABC</td>
            <td>2</td>
            <td>100</td>
            <td>200</td>
        </tr>
        <tr>
            <td>DEF</td>
            <td>1</td>
            <td>300</td>
            <td>300</td>
        </tr>
    </tbody>
</table>

<input id="saveBtn" type="button" value="save">


推荐阅读