【问题标题】:Deleting two cookies on button click单击按钮时删除两个 cookie
【发布时间】:2019-05-03 15:01:07
【问题描述】:

当用户单击我的页面上的链接(具有 deleteCooke 类)时,我想运行一个删除两个 cookie 的函数。

href 本身将控制重定向,因此只想删除(或清除)这两个 cookie。

这两个 cookie 是:langcategory

这是我目前的做法:

/* 1. GET CURRENT COOKIE VALUE */
var lang = $.cookie('lang');
var category = $.cookie('category');

/* 2. DELETE FUNCTION*/
function deleteCookies() {
  var d = new Date();
  d.setTime(d.getTime() - (1000 * 60 * 60 * 24));
  var expires = "expires=" + d.toGMTString();
  window.document.cookie = lang + "=" + "; " + expires;
  window.document.cookie = category + "=" + "; " + expires;
}

/* 3. CALL FUNCTION ON BUTTON CLICK*/
$(document).ready(function() {
  $(".deleteLang").click(function() {
    deleteCookies();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>

<a href="/" class="deleteLang" data-lang="es">Espanyol</a>

但是,使用这种方法,没有一个 cookie 被清除/删除?

编辑

cookie 是如何设置的

$.cookie('lang', 'es', {expires: 2, path: '/'});

当前删除 cookie 的方法

$(document).ready(function() {
   $(".deleteLang").click(function() {
     $.removeCookie('lang', { path: '/' });
     $.removeCookie('lang', '', {expires: 2, path: '/'});
     $.removeCookie('lang'); 
  });
});

【问题讨论】:

  • 你似乎在使用jquery.cookie,所以为什么不这样做:$.removeCookie('buyLang', { path: '/' });
  • @SaniSinghHuttunen - 我之前尝试过类似的方法,但没有成功。我刚试过:$(document).ready(function() { $(".deleteLang").click(function() { $.removeCookie('lang', { path: '/' }); $.removeCookie('category', { path: '/' }); }); }); 还是没有清除 cookie?
  • 你是用路径设置的吗?您是否尝试过仅使用名称而不包括路径来取消设置?
  • @Pete - 我刚刚更新了我的问题以显示 cookie 的设置方式和最新方法

标签: javascript jquery html cookies


【解决方案1】:

这按预期工作。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<a href="/" class="deleteLang" data-lang="es">Espanyol</a>

$.cookie('lang', 'es', {expires: 2, path: '/'});

$(document).ready(function() {
  $(".deleteLang").click(function(e) {
    // Prevent navigation.
    e.preventDefault();

    // Check if the cookie is set
    console.log($.cookie('lang'));

    // Cookie is removed if 'true' is returned.
    console.log($.removeCookie('lang', { path: '/' }));

    // Check that cookie is 'undefined'.
    console.log($.cookie('lang'));
  });
});

如果您检查控制台,您会看到:

es
true
undefined

正如预期的那样。

JSfiddle

【讨论】:

    猜你喜欢
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    相关资源
    最近更新 更多