在页面加载时获取localStorage值

时间:2018-04-04 14:24:45

标签: javascript jquery html css

我搜索了互联网,但我似乎无法找到适合我的任何内容。

以下是代码:

<!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的例子,但我不知道如何在重新加载页面时调用保存的值。

任何帮助都将不胜感激。

提前致谢, 斯蒂芬。

3 个答案:

答案 0 :(得分:1)

本地存储说明

localStorage对象喜欢存储字符串,那么如何存储大型对象,让我们说一些复杂的数据结构呢? - 简单,JavaScript内置了一个简洁的功能,查找JSON.stringify(object)。所以你需要做的就是下面的东西,存储一些复杂的对象就像我下面提供的代码。然后从localStorage中检索一个对象,您想要使用JSON.parse(object);

要查看localStorage,我强烈建议您查看MDN之类的内容,如果您想查看JSON.parseJSON.stringify函数,也可以在这里找到它们:

  1. JSON.parse() link
  2. JSON.stringify() link
  3. &#13;
    &#13;
    // 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);
      }
    });
    &#13;
    &#13;
    &#13;

答案 1 :(得分:1)

您可以使用此JSFiddle:http://jsfiddle.net/xpvt214o/45115/

这里我们使用Cookie概念和jquery.cookie.js来完成您要做的事情。

要正确检查小提琴你需要每次按“运行”,你可以在2个标签中打开相同的小提琴在第一个小提琴中写一些东西然后只需在第二个小提琴标签中按下运行该值应该自动更新,这里 $(function(){});复制您的页面加载

答案 2 :(得分:0)

我的问题并未得到完全解答,但我完全避免在设备上存储信息。现在我只是直接从arduino读取价值而且它有效。但是感谢所有提供帮助的人。