我正在尝试从另一个页面向表中插入一行。使用Javascript。我不想使用ajax或jQuery,因为它看起来有点太复杂了。
我正在解决这个问题:
我在w3学校网站上尝试了不同的东西。我注意到重新加载页面后,更改不会保存。为什么?
我想要的是能够将second.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>
secondPage.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>
答案 0 :(得分:0)
You are trying to save an HTMLElement using LocalStorage, which I believe doesn't work as LocalStorage will only save a key-value pair with strings.
So what I would do is:
1 - Save a stringified version of your table
document.getElementById('myTable').innerHTML
2 - On the second page, create a HTMLElement using the string you saved.
var table = document.createElement('table');
table.innerHTML = localStorage.table;
3 - Edit the table you created on the second page, using table.insertRow, table.insertCell, etc.
4 - Save everything again on localStorage using step 1 hint.
5 - Make sure you load your edited table from localStorage on page 1.
答案 1 :(得分:0)
You can save the table into localStorage, like instructed at Storing table content to HTML5 local storage. But it is different from the method shown above in the original question.
Use setItem method of localStorage:
localStorage.setItem( "tabledata", $("#myTable").html() );
Later you can fetch it like this:
var tabledata = localStorage.getItem( "tabledata" );
$("#tablea").html( tabledata );
However, row = table.insertRow(0)
casted error in my test: Uncaught TypeError: table.insertRow is not a function
. Though I figured out a solution later but it is off the topic.