我写了一个页面,可以向数组中添加数据,添加数据后,刷新后刚刚添加的数据就没了。我的问题是: 怎样才能在数组中添加数据后,下次打开时不被刷新掉。
3条回答 默认 最新
- CSDN专家-天际的海浪 2022-04-05 00:35关注
前端html页面可以把数据保存在localStorage对象中(localStorage对象中的数据在关闭网页后不会消失)。
重新打开页面后再从localStorage对象中取得数据
你题目的解答代码如下:<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <title> 页面名称 </title> </head> <body> <input type="text" id="text" value="xx" /> <input type="button" value="添加到数组" onclick="add();" /> <div id="info"></div> <script type="text/javascript"> var arr = []; if (localStorage.myArray) { arr = JSON.parse(localStorage.myArray); } document.getElementById("info").innerText = JSON.stringify(arr); function add() { arr.push(document.getElementById("text").value); document.getElementById("info").innerText = JSON.stringify(arr); } window.onbeforeunload = function () { localStorage.myArray = JSON.stringify(arr); } </script> </body> </html>
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 微信小程序协议怎么写
- ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
- ¥20 怎么用dlib库的算法识别小麦病虫害
- ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
- ¥15 java写代码遇到问题,求帮助
- ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
- ¥15 有了解d3和topogram.js库的吗?有偿请教
- ¥100 任意维数的K均值聚类
- ¥15 stamps做sbas-insar,时序沉降图怎么画
- ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看