我正在尝试从另一个页面将一行插入到表中。使用 JavaScript。我不想使用 ajax 或 jQuery,因为它看起来有点太复杂了。
我正在通过以下方式解决这个问题:
- 从其他页面获取id表元素
- 单击按钮时插入行
- 保存更改
我尝试了 w3 学校网站上的不同内容。我注意到页面重新加载后更改不会保存。为什么?
我想要的是能够将第二个.php 中的一行添加到index.php 中的表中。
我的代码如下:Javascript 运行但没有添加任何内容:
index.php
<a href="secondPage.php">Go to the second page</a>
<br>
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>
<script>
localStorage.setItem('table', $('#myTable').val());
</script>
第二页.php
<a href="index.php">Go to the first page</a>
<br>
<button onclick="myFunction()">Add to table</button>
<script>
function myFunction() {
var table = localStorage.getItem('table');
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
window.alert(document.getElementById("myTable").rows.length);
}
</script>
最佳答案
您正在尝试使用 LocalStorage 保存 HTMLElement,我认为这不起作用,因为 LocalStorage 只会保存带有字符串的键值对。
所以我会做的是:
1 - 保存表格的字符串化版本
document.getElementById('myTable').innerHTML
2 - 在第二页上,使用您保存的字符串创建一个 HTMLElement。
var table = document.createElement('table');
table.innerHTML = localStorage.table;
3 - 使用 table.insertRow、table.insertCell 等编辑您在第二页上创建的表格
4 - 使用步骤 1 提示将所有内容再次保存在 localStorage 上。
5 - 确保从第 1 页的 localStorage 加载已编辑的表格。
关于javascript - 为什么我的代码无法运行? (尝试从另一页添加一行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48409053/