用jQuery设置cookie

时间:2012-01-29 22:55:33

标签: 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将{​​{1}}的背景设为黄色?

1 个答案:

答案 0 :(得分:3)

嗯,这太容易了:

//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");
 });