Javascript 单击按钮删除两个cookie
当用户单击我的页面上的链接(该链接具有类Javascript 单击按钮删除两个cookie,javascript,jquery,html,cookies,Javascript,Jquery,Html,Cookies,当用户单击我的页面上的链接(该链接具有类deleteCooke)时,我希望运行一个删除两个cookie的函数 href本身将控制重定向,因此只需删除(或清除)两个cookie即可 这两个cookie是:lang和category 以下是我目前的做法: /*1。获取当前COOKIE值*/ var lang=$.cookie('lang'); 变量类别=$.cookie('category'); /* 2. 删除函数*/ 函数deleteCookies(){ var d=新日期(); d、 设置时
deleteCooke
)时,我希望运行一个删除两个cookie的函数
href
本身将控制重定向,因此只需删除(或清除)两个cookie即可
这两个cookie是:lang
和category
以下是我目前的做法:
/*1。获取当前COOKIE值*/
var lang=$.cookie('lang');
变量类别=$.cookie('category');
/* 2. 删除函数*/
函数deleteCookies(){
var d=新日期();
d、 设置时间(d.getTime()-(1000*60*60*24));
var expires=“expires=“+d.togmString();
window.document.cookie=lang+“=”+”;“+过期;
window.document.cookie=类别+“=”+”;“+过期;
}
/* 3. 单击按钮调用函数*/
$(文档).ready(函数(){
$(“.deleteLang”)。单击(函数(){
删除cookies();
});
});代码>
这项工作与预期相符
<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'));
});
});
正如所料
<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'));
});
});
您似乎正在使用jquery.cookie
那么为什么不直接这样做:$.removeCookie('buyLang',{path:'/')代码>?@sanisinghhutunen-我以前尝试过类似的东西,但没有成功。我刚刚试过:$(document).ready(function(){$(“.deleteLang”).click(function(){$.removeCookie('lang',{path:'/'});$.removeCookie('category',{path:'/'});})代码>但它仍然没有清除cookie?您是否使用路径设置它?你有没有试过只用名字而不包括路径来解决它?@Pete-我刚刚更新了我的问题,以展示cookie是如何设置的以及最新的方法