【问题标题】:Cookies html + js adding cookie not working [duplicate]Cookies html + js添加cookie不起作用[重复]
【发布时间】:2020-09-28 21:39:53
【问题描述】:

您好,我有一个脚本,它应该在单击按钮时向上滑动添加 cookie。 但它根本不起作用...... 我尝试了所有但仍然无法正常工作:S

这是我的代码:

<head>
 <script src="jquery.min.js"></script>
 <script>
  $(document).ready(function(){
   $(".btn1").click(function(){
     $("p").slideUp();
   });
  });
 </script>
 <script>
  function iLoveCookies(){
    days=30; // number of days to keep the cookie
    myDate = new Date();
    myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
    document.cookie = 'cookieName=12345; expires=' + myDate.toGMTString();
  }
 </script>
</head>
<body>
  <p>12345 <button class="btn1" onclick="iLoveCookies()">OK</button></p>

感谢您的帮助!

【问题讨论】:

  • 可能是,您在 Chrome 中检查本地 html 文件的 cookie?我问是因为您的代码在 IE 中工作,但 Chrome 不会为本地文件保存 cookie。此外,为什么不直接将iLoveCookies() 调用添加到$(".btn1").click(function(){ 而不是以两种不同的方式分配两个onclick 事件(这不会影响结果,只是对我来说似乎更合适)。
  • 感谢您对我的帮助。脚本现在可以工作了!

标签: javascript jquery html cookies


【解决方案1】:

查看 jquery.cookie:https://github.com/js-cookie/js-cookie

<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $.cookie('the_cookie', 'the_value'); // default expires: 365
        $.cookie('the_cookie', 'the_value', { expires: 7 }); // expiring in 7 days 
        console.log($.cookie('the_cookie')); // => "the_value"
    });
</script>

P.S.:您需要通过网络服务器。在浏览器中打开html文件是不行的。

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
  • 谢谢。我已经更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-13
  • 1970-01-01
  • 2014-10-29
  • 1970-01-01
  • 2018-02-25
相关资源
最近更新 更多