gpt4 book ai didi

javascript - 如何显示从 localstorage 获取的数据到一个简单的 HTML 页面

转载 作者:行者123 更新时间:2023-11-30 20:01:06 24 4
gpt4 key购买 nike

我试图将数据保存在 submit.html 页面上。数据存储在 localstorage 上,我希望每次访问该页面时输入的数据始终在表中。目前它仅在提交事件时可见。当我返回带有另一个条目的 submit.html 页面时,之前的数据消失了。

这是代码。

1 - index.html

<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h1>User Registration Form</h1>
<form action="submit.html" onsubmit="callme()">
Name:<br>
<input id="name" type="text">
<br>
Adress:<br>
<input id="address" type="text">
<br>
Email:<br>
<input id="email" type="email">
<br>
Phone:<br>
<input id="phone" type="number">
<br><br>
<input type="submit" value="Submit">
<input type="reset" value="Reset" name="Reset">
</form>
<script>
function callme(){
var name = document.getElementById('name').value;
localStorage.setItem('name', name);
var address = document.getElementById('address').value;
localStorage.setItem('address', address);
var email = document.getElementById('email').value;
localStorage.setItem('email', email);
var phone = document.getElementById('phone').value;
localStorage.setItem('phone', phone);

}
</script>
</body>
</html>

2 - submit.html

<!DOCTYPE html>
<html>
<head>
<title>Detail Page</title>
</head>
<body>
<h1>User Detail Page</h1>
<div id="result-table">
<table border="1">
<tr>
<th>Name</td>
<th>Address</td>
<th>Email</th>
<th>Phone</td>
</tr>
<tr>
<td id="first"></td>
<td id="second"></td>
<td id="third"></td>
<td id="fourth"></td>
</tr>
</table>
<br>
</div>

<script>
window.onload = function() {
document.getElementById('first').innerText = localStorage.getItem('name');
document.getElementById('second').innerText = localStorage.getItem('address');
document.getElementById('third').innerText = localStorage.getItem('email');
document.getElementById('fourth').innerText = localStorage.getItem('phone');

};
</script>
<form action="/index.html">
<button >Go Back</button>
</form>
</body>
</html>

最佳答案

我从你的代码中了解到,你用以前的数据覆盖了现有数据,而不是将值设置为本地存储中的单个键创建并在本地使用以前数据的副本,并在你提交时向其中添加新数据如果您可以提交多个表单并显示在表格中。

var name = document.getElementById('name').value;
var address = document.getElementById('address').value;
var email = document.getElementById('email').value;
var phone = document.getElementById('phone').value;

let formData = {};
formData.name = name;
formData.email = email;
formData.address = address;
formData.phone = phone;

let formDataArry = localStorage.getItem('formDataArry') || []

formDataArry.push(formData)

localStorage.setItem('formDataArry',formDataArry )

然后您可以循环表中的数组以从本地存储中获取包含数据的表

关于javascript - 如何显示从 localstorage 获取的数据到一个简单的 HTML 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53372096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com