JavaScript Cookie封装类源码及使用方法

JavaScript操作Cookie着实麻烦,这也是很多Web开发者比较头痛的一块。JavaScript Cookie写起来可能不是很难,但是要写出漂亮的代码就不那么简单了。以前写过几个函数来方便JS操作Cookie(JavaScript Cookie操作我不怕了),今天再献上一个JavaScrip Cookie操作的封装类。

JavaScript Cookie封装类源码
  1. String.prototype.format = function() {
  2. var s = this;
  3. for (var i = 0, j = arguments.length; i < j; i++)
  4. s = s.replace("{" + (i) + "}", arguments[i]);
  5. return(s);
  6. }
  7. var Cookie = {
  8. Set : function () {
  9. var name = arguments[0], value = escape(arguments[1]),
  10. days = (arguments.length > 2) ? arguments[2] : 365,
  11. path = (arguments.length > 3) ? arguments[3] : "/";
  12. with(new Date()) {
  13. setDate(getDate() + days);
  14. days = toUTCString();
  15. }
  16. document.cookie = "{0}={1};expires={2};path={3}".format(name, value, days, path);
  17. },
  18. Get : function () {
  19. var returnValue = document.cookie.match(new RegExp("[\b\^;]?" + arguments[0] + "=([^;]*)(?=;|\b|$)","i"));
  20. return returnValue ? unescape(returnValue[1]) : returnValue;
  21. },
  22. Delete : function () {
  23. var name = arguments[0];
  24. document.cookie = name + "=1 ; expires=Fri, 31 Dec 1900 23:59:59 GMT;";
  25. }
  26. }

看一下使用方法吧。

JavaScript Cookie类使用方法
  1. <script type="text/javascript">
  2. Cookie.Set("MyCookie", "Cookie值");
  3. Cookie.Get("MyCookie");
  4. Cookie.Delete("MyCookie")
  5. </script>
版块:开发文档 Tags: , 时间:2010-01-07
文章评论
0 回复 for "JavaScript Cookie封装类源码及使用方法"
phplamp - 2010-03-12
您好,您的评论将出现在这里!
评论表单