2012-01-29 87 views
0

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

下面是一些示例代码:

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

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

我怎样才能保持#whatever的背景黄经饼干吗?

回答

3

嗯,这是易peasy:

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

完美!谢谢。 – UserIsCorrupt 2012-01-29 23:07:02

+1

:)如果它是完美的,你能接受答案吗? – 2012-01-29 23:08:02