JQuery中使用cookie记住背景颜色

     换背景颜色是很多网站上经常用到的,当刷新网页时必须要记住当前的背景颜色,这时就要使用Cookie实现。下面请看程序:

   

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title></title>
 5 
 6     <script src="js/jquery-1.4.2.js" type="text/javascript"></script>
 7 
 8     <script src="js/jquery.cookie.js" type="text/javascript"></script>
 9 
10     <script type="text/javascript">
11         $(function() {
12             $("#tables td").click(function() {
13                 $("body").css("background-color", $(this).css("background-color"));
14                 $.cookie("background", $(this).css("background-color"));
15             });
16             if ($.cookie("background")) {
17                 $("body").css("background-color", $.cookie("background"));
18             }
19         });
20     </script>
21 
22 </head>
23 <body>
24     <table id="tables">
25         <tr>
26             <td style="background-color: Red;">
27                 红色
28             </td>
29             <td style="background-color: Yellow;">
30                 黄色
31             </td>
32             <td style="background-color: Green;">
33                 绿色
34             </td>
35         </tr>
36     </table>
37 </body>
38 </html>

    在以上程序中定义了一个table,其中table中有一个tr,tr中有三个含有背景颜色的td。先遍历td,为每一个td添加click事件;当单击td时将网页的背景颜色设置为当前td的颜色,使用

   $("body").css("background-color",$(this).css("background-color"));注意:在body的css中可以使用background也可以使用background-color,但是在$(this)的css中只能使用background-color,不然没有效果。并且将td的background-color赋值给cookie。最后进行判断,当网页加载后,cookie是否为空,如果不为空则将cookie中的值赋给body的css中的background-color。

posted @ 2012-06-11 16:35  孙进  阅读(1384)  评论(0编辑  收藏  举报