获取页面加载时的localStorage值 [英] Get localStorage value on page load

查看:71
本文介绍了获取页面加载时的localStorage值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索过互联网,但似乎找不到适合我的任何东西.

I've searched the internet but I can't seem to find anything that works for me.

这是代码:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Heating System Control</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
        strLED1 = "";
        strLED2 = "";
        strText1 = "";
        strText2 = "";
        var LED1_state = 0;
        var LED2_state = 0;
        function GetArduinoIO()
            {
                nocache = "&nocache=" + Math.random() * 1000000;
                var request = new XMLHttpRequest();
                request.onreadystatechange = function()
                {
                    if (this.readyState == 4) {
                        if (this.status == 200) {
                            if (this.responseXML != null) 
                            {
                            // XML file received - contains analog values, switch values and LED states
                                document.getElementById("input1").innerHTML =
                                    this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
                                document.getElementById("input2").innerHTML =
                                    this.responseXML.getElementsByTagName('analog')[1].childNodes[0].nodeValue;
                                // LED 1
                                if (this.responseXML.getElementsByTagName('LED')[0].childNodes[0].nodeValue === "on") {
                                    document.getElementById("LED1").innerHTML = "ON";
                                    document.getElementById("LED1").style.backgroundColor = "green";
                                    document.getElementById("LED1").style.color = "white";
                                    LED1_state = 1;
                                }
                                else {
                                    document.getElementById("LED1").innerHTML = "OFF";
                                    document.getElementById("LED1").style.backgroundColor = "red";
                                    document.getElementById("LED1").style.color = "white";
                                    LED1_state = 0;
                                }
                                // LED 2
                                if (this.responseXML.getElementsByTagName('LED')[1].childNodes[0].nodeValue === "on") {
                                    document.getElementById("LED2").innerHTML = "ON";
                                    document.getElementById("LED2").style.backgroundColor = "green";
                                    document.getElementById("LED2").style.color = "white";
                                    LED2_state = 1;
                                }
                                else {
                                    document.getElementById("LED2").innerHTML = "OFF";
                                    document.getElementById("LED2").style.backgroundColor = "red";
                                    document.getElementById("LED2").style.color = "white";
                                    LED2_state = 0;
                                }
                            }
                        }
                    }
                }
                // send HTTP GET request with LEDs to switch on/off if any
                request.open("GET", "ajax_inputs" + strLED1 + strLED2 + nocache, true);
                request.send(null);
                setTimeout('GetArduinoIO()', 1000);
                strLED1 = "";
                strLED2 = "";
            }
        function GetButton1()
            {
                if (LED1_state === 1) 
                {
                    LED1_state = 0;
                    strLED1 = "&LED1=0";
                }
                else 
                {
                    LED1_state = 1;
                    strLED1 = "&LED1=1";
                }
            }
        function GetButton2()
            {
                if (LED2_state === 1) 
                {
                    LED2_state = 0;
                    strLED2 = "&LED2=0";
                }
                else 
                {
                    LED2_state = 1;
                    strLED2 = "&LED2=1";
                }
            }
        function SendText1()
            {
                nocache = "&nocache=" + Math.random() * 1000000;
                var request = new XMLHttpRequest();

                strText2 = "&txt2=" + document.getElementById("txt_form1").form_text1.value + "&end2=end";

                request.open("GET", "ajax_inputs" + strText2 + nocache, true);
                request.send(null);
            }
        function SendText2()
            {
                nocache = "&nocache=" + Math.random() * 1000000;
                var request = new XMLHttpRequest();

                strText1 = "&txt1=" + document.getElementById("txt_form2").form_text2.value + "&end1=end";

                request.open("GET", "ajax_inputs" + strText1 + nocache, true);
                request.send(null);
            }
        function clsTxt1()
            {
            setTimeout(
              function clearTxt()
              {
                  document.getElementById("txt_form1").form_text1.value = "";
              }, 500)
            }
        function clsTxt2()
            {
            setTimeout(
              function clearTxt()
              {
                  document.getElementById("txt_form2").form_text2.value = "";
              }, 500)
            }
        function Threshold1()
        {
            var thr1 = document.getElementById("txt_form1").form_text1.value;
            document.getElementById("thresh1").innerHTML = thr1;
        }
        function Threshold2()
            {
                var thr2 = document.getElementById("txt_form2").form_text2.value;
                document.getElementById("thresh2").innerHTML = thr2;
            }
    </script>
    <style>
        .IO_box 
        {
            float: left;
            margin: 0 20px 20px 0;
            border: 1px solid black;
            padding: 0 5px 0 5px;
            width: 100px;
            height: 196px;
            text-align: center;
        }
        h1 
        {
            font-family: Helvetica;
            font-size: 120%;
            color: blue;
            margin: 5px 0 10px 0;
            text-align: center;
        }
        h2 
        {
            font-family: Helvetica;
            font-size: 85%;
            color: black;
            margin: 10px 0 5px 0;
            text-align: center;
        }
        p, form
        {
            font-family: Helvetica;
            font-size: 80%;
            color: #252525;
            text-align: center;
        }
        button
        {
            font-family: Helvetica;
            font-size: 80%;
            max-width: 100px;
            width: 90px;
            height: 25px;
            margin: 0 auto;
            text-align: center;
            border: none;
        }
        input
        {
            font-family: Helvetica;
            font-size: 80%;
            max-width: 100px;
            width: 90px;
            height: 25px;
            margin: 0 auto;
            text-align: center;
            border: none;
        }
        .small_text 
        {
            font-family: Helvetica;
            font-size: 70%;
            color: #737373;
            text-align: center;
        }
        textarea
        {
            resize: none;
            max-width: 90px;
            margin-bottom: 1px;
            text-align: center;
        }
    </style>
    </head>
    <body onload="GetArduinoIO(); Threshold1()">
        <h1>Heating System Control</h1>
        <div class="IO_box">
            <h2>Room One</h2>
            <p>Temp1 is: <span id="input1">...</span></p>
            <button type="button" id="LED1" onclick="GetButton1()" color="white" backgroundColor="red" style="border: none;">OFF</button><br /><br />
            <form id="txt_form1" name="frmText">
                <textarea name="form_text1" rows="1" cols="10"></textarea>
            </form>
            <input type="submit" value="Set Temp" onclick="SendText1(); clsTxt1(); Threshold1();" style ="background-color:#5F9EA0" />
            <p>Threshold: <span id="thresh1">...</span></p>
        </div>
        <div class="IO_box">
            <h2>Room Two</h2>
            <p>Temp2 is: <span id="input2">...</span></p>
            <button type="button" id="LED2" onclick="GetButton2()" color="white" backgroundColor="red" style="border: none;">OFF</button><br /><br />
            <form id="txt_form2" name="frmText">
                <textarea name="form_text2" rows="1" cols="10"></textarea>
            </form>
            <input type="submit" value="Set Temp" onclick="SendText2(); clsTxt2(); Threshold2();" style ="background-color:#5F9EA0" />
            <p>Threshold: <span id="thresh2">...</span></p>
        </div>

    </body>
</html>

所以我的问题是,即使重新加载页面后(从"Threshold1()"函数),如何仍可以将插入值插入文本区域?我发现了一些有关"localStorage"和JQuery的示例,但是我不知道在重新加载页面时如何调用保存的值.

So my question is, How can I keep the value inserted in the text area even after I reload the page (from the "Threshold1()" function)? I found a few examples with "localStorage" and JQuery, but I have no idea how to call the saved value when I reload the page.

任何帮助将不胜感激.

预先感谢, 斯蒂芬.

推荐答案

本地存储说明

localStorage对象喜欢存储字符串,那么如何存储大型对象(比如说一些复杂的数据结构)呢? -简单,JavaScript内置了一个简单的函数,查找JSON.stringify(object).因此,您所需要做的只是像下面这样来存储一些复杂的对象,就像我下面提供的代码一样.然后要从localStorage检索对象,您将要使用JSON.parse(object);.

Local Storage Explained

The localStorage object likes to store strings, so how would one store large objects, let's say some complex data structure? - Simple, JavaScript has a neat function built in, look up JSON.stringify(object). So all you would need to do is something like below to store some complex object is something like the code I've provided below. Then to retrieve an object from the localStorage you'll want to use JSON.parse(object);.

要研究localStorage,我强烈建议您看一下 MDN ,如果您想查看JSON.parseJSON.stringify函数,也可以在这里找到它们:

To look into localStorage, I strongly suggest you take a look at the likes of MDN and if you want to look into the JSON.parse and JSON.stringify functions, you can also find them both here:

  1. JSON.parse() 链接
  2. JSON.stringify() 链接
  1. JSON.parse() link
  2. JSON.stringify() link

// vanilla js version of $(document).ready(function(){/*code here*/});
window.ready = function(fnc) {
  if (typeof fnc != "function") {
    return console.error("You need to pass a function as a param.");
  }

  try { // try time out for some old IE bugs
    setTimeout(function () {
      document.addEventListener("DOMContentLoaded", fnc());
    }, 10)
  } catch (e) {
    try { // sometimes timeout won't work
      document.addEventListener("DOMContentLoaded", fnc());
    } catch (ex) {
      console.log(ex);
    }
  }
};

// shorter than $(document).ready();
ready(function() {
  var object = {
      name: "Jack",
      age: 30,
      location: "U.S.A.",
      get_pay: function() {
        console.log("test");
      }
    },
    test;

  console.log(object);

  var obj_string = JSON.stringify(object);

  // run a test
  var run_test = function() {
    // output the stored object 
    test = localStorage.getItem("test");
    console.log(test);

    // to make js turn it into an object again 
    test = JSON.parse(localStorage.getItem("test"));
    console.log(test);
  };


  // demo of trying to store an actual object
  try {
    localStorage.setItem("test", object);
    run_test();
  } catch (e) {
    console.log(e);
  }

  // demo of trying to store the string
  try {
    localStorage.setItem("test", obj_string);
    run_test();
  } catch (e) {
    console.log(e);
  }
});

这篇关于获取页面加载时的localStorage值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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