首页 > 解决方案 > 如何在javascript中将选定的表行值发送到另一个页面

问题描述

我有 2 页和 2 个表,在第 1 页(表 1)我想将选定的行发送到第 2 页(表 2),在表 2 中我显示选定的行

这是第 1 页中的第一个表:

<table class="src-table">
    <tr>
        <th>Select</th>
        <th>Firstname</th>
    </tr>
    <tr>
        <td>
            <input type="checkbox">
        </td>
        <td>Jill</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox">
        </td>
        <td>Eve</td>
    </tr>
</table>
<br>
<input type="button" value="Submit" id="submit">

像下面的图片在此处输入图像描述

这是第 2 页中的第二个表格:

<table class="target-table">
    <tr>
        <th>Select</th>
        <th>Firstname</th>
    </tr>
</table>

像下面的图片在此处输入图像描述

标签: javascriptjqueryhtmlcheckbox

解决方案


如果你真的需要这个。您可以使用localStorage.

localStorage不在沙箱中工作。但是您也可以在您的应用程序中使用它。

storeItems当您需要保存所选内容以存储(例如在元素选择上)时运行在目标表页面上的appendStoredToAnouther窗口事件上运行window.onload

function storeItems() {
  const selectedItems = document.querySelectorAll("#first-table .selected");
  const selectedHtml = nodeListToString(selectedItems);
  
  localStorage.add('selectedTableItems', selectedHtml);
}

function nodeListToString(nodeList) {
  let string = '';
  nodeList.forEach(function(node) {
    string += node.outerHTML;
  });
  return string;
}

function appendStoredToAnouther() {
  const itemsHtml = window.localStorage.get('selectedTableItems');
  
  const targetTable = document.getElementById('target-table');
  targetTable.innerHTML = itemsHtml + targetTable.innerHTML;
}
<table id="first-table">
  <tr class="selected">
    <td>1</td>
    <td>Selected</td>
    <td>Item</td>
  </tr>
  <tr class="selected">
    <td>1</td>
    <td>Selected</td>
    <td>Item</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Not Selected</td>
    <td>Item</td>
  </tr>
</table>

<button type="button" onclick="storeItems()">Send to anouther</button>
<button type="button" onclick="appendStoredToAnouther()">Append stored to anouther</button>

<table id="target-table">
  <tr class="selected">
    <td>1</td>
    <td>Selected</td>
    <td>Item</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Not Selected</td>
    <td>Item</td>
  </tr>
</table>


推荐阅读