javascript - 使用 jQuery 设置 cookie

标签 javascript jquery cookies

我搜索了有关如何使用 jQuery 设置 cookie(使用 jQuery cookie 插件)的教程,它们似乎都面向比我更有经验的人。

这是一些示例代码:

<button>Example</button>
<div id="whatever" style="background:red;">Test</div>

<script>
 $('button').click(function() {
  $('#whatever').css("background","yellow");
 });
</script>

如何通过 cookie 将 #whatever 的背景保持为黄色?

最佳答案

嗯,这很简单:

//on document ready, checks if the cookie is set, and if so, sets the background with it's value
$(function(){
  if($.cookie("background") != null){
     $('#whatever').css("background", $.cookie("background"));
  }
});
//here you set the cookie, with the value you want
$('button').click(function() {
  $('#whatever').css("background","yellow");
  $.cookie("background", "yellow");
 });

关于javascript - 使用 jQuery 设置 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9057526/

相关文章:

javascript - 根据域和名称的范围删除重复的 JavaScript cookie

javascript - Node JS cookie 解析器不工作

javascript - 变量的选定选项属性

javascript - 在更改事件上调用函数时出现问题

javascript - 如何使用 Meteor 创建异步 RESTful 接口(interface)

jQuery Ui Slider - 工具提示仅显示在幻灯片上

javascript - jQuery 的 $.post 二进制文件安全吗?

javascript - JQuery:如何检查表单字段的值

javascript - 如何将简单值从 axios.post 发送到 asp.net 核心?

php - 需要将 json 值转换为来自 cookie 的变量