当用户单击我的页面上的链接(具有 deleteCooke
类)时,我想运行一个删除两个 cookie 的函数。
href
本身将控制重定向,因此只想删除(或清除)这两个 cookie。
这两个 cookie 是:lang
和 category
。
这是我当前的方法:
/* 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');
});
});
最佳答案
这按预期工作。
<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
正如预期的那样。
关于javascript - 单击按钮时删除两个 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55953761/