页面刷新时如何保留javascript数组? [英] How to retain javascript array while page refresh?

查看:57
本文介绍了页面刷新时如何保留javascript数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP文件

<input type="text" id="txtMyText">
<button type="button" id="myButton" onclick="addItemToArray()">Add to Array</button>

JavaScript文件

var myArray = []

function addItemToArray()
{
    myArray.push(document.getElementById("txtMyText").value);
}

每当我在文本字段中输入一些值并单击按钮时,值就会存储在数组中.刷新页面后,我的数组变为空.我想保留其元素,直到手动删除它们.我该如何留住他们?我应该在PHP会话或隐藏字段中放置数组吗?如果是,那怎么办?

Whenever I enter some value in a text field and hit the button, value gets stored in the array. When a page is refreshed, my array becomes empty. I want to retain its elements until I remove them manually. How do I retain them? Should I put array in PHP session or hidden field? If yes, then how?

推荐答案

为此目的使用 localStorage API,使用 setItem()方法并在存储之前对数组进行字符串化放入 localStorage .您可以通过 getItem()检索存储的项目,并使用 JSON.parse()解析存储的数组,类似

Use localStorage API for this purpose, Use setItem() method and do stringify the array before storing into the localStorage. You can retrieve the stored item by getItem() and parse the stored array using JSON.parse(), something like

if(localStorage.getItem('textValues') == null){
    var myArray =[];
}else{
    myArray =  JSON.parse(localStorage.getItem('textValues'));
   //-----------^parse the item by getting---^--stored item
}

function addItemToArray(){
    myArray.push(document.getElementById("txtMyText").value);
    localStorage.setItem('textValues', JSON.stringify(myArray));
    //------------^store the item by stringify--^
}

演示

这篇关于页面刷新时如何保留javascript数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆