如何使用localStorage保存具有随机值的变量

时间:2016-01-14 07:55:42

标签: javascript local-storage

我试图使用localStorage来保存一个变量,该变量具有从JavaScript文件中的数组中随机生成的值,并将其传递给另一个HTML文件。但是,Javascript文件(Random_Msg)中的值和HTML文件中的值(Random_Msg1)不一样,意味着它没有保存,而是随机生成另一个值。

这些是生成变量并保存在localStorage中的代码:

function CreateRandomMsg(){
var RandomMsg = Msgs_Arr[Math.floor(Math.random()* Msgs_Arr.length)];
return RandomMsg;
}

var Random_Msg = CreateRandomMsg();

function alertMsg(){
alert(Random_Msg);
}
window.localStorage.setItem("Random_Msg1",Random_Msg);

在我的HTML文件中,我首先检索了变量:

var Random_Msg1 = window.localStorage.getItem("Random_Msg1");

并在if语句中使用它:

if (Random_Msg1 == Msgs_Arr[0] || Random_Msg1 == Msgs_Arr[1]){
     value = facesDet.photos[0].tags[0].attributes.glasses.value;
     confidence = facesDet.photos[0].tags[0].attributes.glasses.confidence;
    } else if (Random_Msg1 == Msgs_Arr[2] || Random_Msg1 == Msgs_Arr[3]) {
      value = facesDet.photos[0].tags[0].attributes.smiling.value;
      confidence = facesDet.photos[0].tags[0].attributes.smiling.confidence;
    };

1 个答案:

答案 0 :(得分:1)

如果pageload中存在必要密钥的值,您可以查看localStorage。如果缺少值,则计算并保存新值。您还可以使用额外的事件来覆盖此键的值,但这将是用户操作。

注意: Stack Overflow无法访问localStorage,任何测试都应该在JSFiddle上完成。

示例

JSFiddle



function computeRandomValue() {
  var data = ["test", "test1", "test2", "test3", "test4"];
  var index = Math.floor(Math.random() * 10) % data.length;
  return data[index];
}

function setToLocalStorage(newVal) {
  var lsKey = "_lsTest";
  localStorage.setItem(lsKey, newVal);
}

function getFromLocalStorage() {
  var lsKey = "_lsTest";
  return localStorage.getItem(lsKey);
}

function initializePage() {
  var _val = getFromLocalStorage();

  if (!(_val && _val.trim().length > 0)) {
    _val = computeAndSaveNewValue();
  }

  printValue(_val, "lblResult");
}

function computeAndSaveNewValue() {
  var newVal = computeRandomValue();
  setToLocalStorage(newVal);
  printValue(newVal);
  return newVal;
}

function printValue(value) {
  var id = "lblResult";
  document.getElementById(id).innerHTML = value;
}

(function() {
  window.onload = initializePage;
})()

<p id="lblResult"></p>
<button onclick="computeAndSaveNewValue()">Save new Value</button>
&#13;
&#13;
&#13;