2014-01-27 54 views
0

对不起,坏标题。对于我的生活,我无法找到一个好办法做到这一点。我有一个 用于设置cookie的jquery对象。在我的代码中,我使用该cookie 来收集来自用户的信息以及执行各种其他功能。在某些情况下,问题是 我不希望cookie名称为'user-profile'我希望它是'admin-profile'。 有没有办法在我拨打userProfile()并更改cookie名称时以某种方式传递选项?我想 的管理员配置文件' cookie基本上做的一切'用户配置文件' cookie。我是一个新手,所以代码示例对我来说最适合。jquery - 通过参数更改jquery对象

;(function($){ 
    $.fn.userProfile = function(opts) { 

     var userProfileCookie = { 
      name: 'user-profile', 
      options: { 
       path: '/', 
       expires: 365 
      } 
     }; 

     function userHeightCookie() { 
      var userData = $.parseJSON($.cookie(userProfileCookie.name)); 
      return(userData); 
     }; 

     function readHeightCookie(userInfo) { 
      $.cookie(userProfileCookie.name, JSON.stringify(userInfo), userProfileCookie.options); 
     }; 

     function removeProfileCookie() { $.cookie(userProfileCookie.name, null, userProfileCookie.options); } 

     if($(".slider").length > 0){ 
      $.cookie(userProfileCookie.name); 
     } 
    }})(jQuery); 

$(document).ready(function() { $('#mastHead').userProfile(); }); 

回答

1

使用opts参数如下:

;(function($){ 
    $.fn.userProfile = function(opts) { 

     var name = (opts.name || 'user') + '-profile'; 
     var userProfileCookie = { 
      name: name, 
      options: { 
       path: '/', 
       expires: 365 
      } 
     }; 

     function userHeightCookie() { 
      var userData = $.parseJSON($.cookie(userProfileCookie.name)); 
      return(userData); 
     }; 

     function readHeightCookie(userInfo) { 
      $.cookie(userProfileCookie.name, JSON.stringify(userInfo), userProfileCookie.options); 
     }; 

     function removeProfileCookie() { $.cookie(userProfileCookie.name, null, userProfileCookie.options); } 

     if($(".slider").length > 0){ 
      $.cookie(userProfileCookie.name); 
     } 
    }})(jQuery); 

$(document).ready(function() { $('#mastHead').userProfile({ name: 'admin' }); }); 
+0

天才!感谢@Barmar –