2012-08-10 61 views
7

我正在使用jquery-cookie库与JQuery创建cookie。我怎样才能更新cookie的价值?我需要它创建新的cookie,如果cookie存在来更新它。我怎样才能做到这一点? 代码,我得到:jQuery更新cookie值

v.on('click', function(){ 
     var d = $(this).attr('role');  
     if(d == 'yes') 
      { 
      glas = 'koristan.' 
      }else { 
       glas = 'nekoristan.' 
      }; 
     text = 'Ovaj komentar vam je bio ' + glas; 

     //This part here create cookie 
     if(id_u == 0){ 
      $.cookie('010', id + '-' + d); 
     }   
     $.post('<?php echo base_url() ?>rating/rat_counter', {id : id, vote : d, id_u : id_u}, function(){ 
     c.fadeOut('fast').empty().append('<p>' + text).hide().fadeIn('fast'); 
     }); 
    }) 

回答

9

要更新一个cookie,所有你需要做的是创建具有相同的名称和不同值的cookie。

编辑

到新的价值附加到老......

//Im not familiar with this library but 
//I assume this syntax gets the cookie value. 
var oldCookieValue = $.cookie('010'); 
//Create new cookie with same name and concatenate the old and new desired value. 
$.cookie('010', oldCookieValue + "-" + id); 
+0

我需要它新的字符串追加到老。这个怎么做? – Sasha 2012-08-10 13:34:33

+1

获取cookie并将其附加到“新”cookie。我将添加更新到我的答案。 – marteljn 2012-08-10 13:35:41

+0

它工作得很好。感谢您的帮助 :) – Sasha 2012-08-10 13:42:26

1

注意这个环节

http://www.electrictoolbox.com/jquery-cookies/

在这里你可以看到所有重要的事情,你可以用cookies来做。

如果你想知道一个饼干已经存在

,只要使用这个

if($.cookie("example") != null) 
{ 
    //cookie already exists 
}