简体   繁体   English

将值从Cookie存储到JavaScript变量

[英]Store value from cookie to JavaScript variable

I'm just getting started with JavaScript & jQuery and am figuring things out as I go, so apologies if this is a basic question. 我刚刚开始使用JavaScript和jQuery,并在进行过程中弄清楚了一切,如果这是一个基本问题,我们深表歉意。 I have some simple code written to: 我写了一些简单的代码:

  • Capture a value from a form 从表单中获取值
  • Store it to a cookie 将其存储到cookie
  • Recall the value from the cookie and store it in a JS variable 从cookie中调出值并将其存储在JS变量中
  • Print the JS variable 打印JS变量

...but I can't get it to work. ...但是我无法正常工作。 I can see that the cookie is being set properly, but for some reason, I can't retrieve it and write it to the variable. 我可以看到cookie设置正确,但是由于某种原因,我无法检索它并将其写入变量。 Here is my code, any help would be much appreciated! 这是我的代码,任何帮助将不胜感激!

<!-- CAPTURE A VALUE IN A SIMPLE FORM... -->
  <input id="txt" type="text" value="foo" />
  <input id="btn" type="button" value="1 - write cookie" />
  <input id="btntwo" type="button" value="2 - set cookie to variable" />
  <input id="btnthree" type="button" value="3 - print the cookie" />

<!-- WRITE THE VALUE TO THE COOKIE WHEN A USER CLICKS THE BTN... -->
  <script type="text/javascript">                                         
   $(document).ready(function () {
    $("#btn").on("click", function () {
      $.cookie('myCookie', $("#txt").val(), { expires: 365 });
      });
    });                              
  </script> 

<!-- SET THE COOKIE VALUE TO A VARIABLE WHEN A USER CLICKS THE BTNTWO... -->
<script type="text/javascript">   
$(document).ready(function() {
  $("#btntwo").on("click", function () {
    var cookVal = $.cookie('myCookie')
  });
});
</script>     

<!-- PRINT THE COOKIE VALUE ON THE SCREEN WHEN A USER CLICKS THE BTNTHREE... -->
<script type="text/javascript">   
$(document).ready(function() {
  $("#btnthree").on("click", function () {
    document.write(cookVal);     
  });
});
</script>     

Your cookVal variable is local to the click-handler function, anything outside will not be able to access it. 您的cookVal变量位于点击处理函数的本地,所有外部内容都将无法访问它。

Also, do not use document.write in event handlers. 另外,请勿在事件处理程序中使用document.write If the HTML is fully parsed (and the DOM ready), the document is closed. 如果完全解析了HTML(并且DOM准备就绪),则文档将关闭。 Calls to document.write after that will clear it and rewrite it. 之后调用document.write将清除并重写它。

Btw, you might join your separate scripts to a single one, that might make the code more readable. 顺便说一句,您可能将单独的脚本连接到一个脚本中,这可能会使代码更具可读性。

<input id="txtin" type="text" value="foo" />
<button id="btn">write cookie</button>
<button id="btntwo">2 - set cookie to variable</button>
<button id="btnthree">3 - print the cookie</button>
<output id="txtout" />

<script type="text/javascript">                                         
$(document).ready(function () {
  <!-- WRITE THE VALUE TO THE COOKIE WHEN A USER CLICKS THE BTN... -->
  $("#btn").on("click", function () {
    $.cookie('myCookie', $("#txtin").val(), { expires: 365 });
  });
  <!-- SET THE COOKIE VALUE TO A VARIABLE WHEN A USER CLICKS THE BTNTWO... -->
  var cookVal; // declared local to the whole onready function
  $("#btntwo").on("click", function () {
    cookVal = $.cookie('myCookie');
  });
  <!-- PRINT THE COOKIE VALUE ON THE SCREEN WHEN A USER CLICKS THE BTNTHREE... -->
  $("#btnthree").on("click", function () {
    $("#txtout").val(cookVal);     
  });
});
</script>

Demo at jsfiddle.net jsfiddle.net上的演示

First of all, you don't need multiple $(document).ready methods. 首先,您不需要多个$(document).ready方法。

What gets outputted when you try: 尝试时输出的内容:

$(document).ready(function () {

    $("#btn").on("click", function () {
       $.cookie('myCookie', $("#txt").val(), { expires: 365 });
    });                              

    var cookVal = 'NOT SET';

    $("#btntwo").on("click", function () {
       cookVal = $.cookie('myCookie')
    });

    $("#btnthree").on("click", function () {
       document.write(cookVal);     
    });

});

If you look at your JavaScript for the #btn onclick, the syntax for saving the cookie is wrong. 如果您查看#btn onclick的JavaScript,则保存cookie的语法是错误的。 You're adding an extra }) which will break the script. 您要添加一个额外的}) ,这将破坏脚本。 If you're ever unsure, use the Developer Tools in Chrome or Firebug in Firefox and look at your console. 如果不确定,请使用Chrome中的开发人员工具或Firefox中的Firebug,然后查看您的控制台。 JavaScript errors are outputted there. JavaScript错误在那里输出。

you do not have to put each of these in a separate $(document).ready(function() you can just put them all in one. Also the shorthand for this is: 您不必将每一个都放在单独的$(document).ready(function()中,只需将它们全部放在一个。

$(function(){
............
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM