gpt4 book ai didi

javascript - 如何在第二次点击后销毁cookie

转载 作者:行者123 更新时间:2023-12-01 08:32:42 24 4
gpt4 key购买 nike

我在 cookie 中存储了一个按钮颜色,这样如果按钮单击,则 css 颜色在页面刷新后保留,但我不知道如何在第二次单击后销毁 cookie,所以如果用户再次单击该按钮颜色回到原来,我使用jquery cookie插件

jquery:

var color = Cookies.get('color')
console.log(color)

if(color)
$('.likes-button').addClass(color)
Cookies.remove('color')

$('.likes-button').click(function(){
var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
var el= this;
var ajaxdata = $(this).attr('data-id');
var ajaxstring = $(this).attr('string');
console.log(ajaxstring)

$.ajax({
type: "POST",
url: '/ajax/upvote/',
data: JSON.stringify({'product_id' : ajaxdata,'string': ajaxstring}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-CSRFToken": csrftoken
},
success: function(response) {
var up = response['likes']
var string = response['string']
console.log(string);
console.log(up)
$(el).find('.target').html(up);
$(el).find('.string').html(string);
$('.likes-button').toggleClass(color)
Cookies.set('color', 'heart')
}
})
})



CSS

.heart i.fa-heart{
color : #f44336
}

最佳答案

您可以添加一个 if block 来检查 cookie 是否已设置。如果 cookie 已设置,则将其删除,否则添加它。

示例:

if(Cookies.get('color')) {
Cookies.remove('color');
} else {
Cookies.set('color', 'heart');
}

完整代码

let color = Cookies.get("color");
if (color) {
$(".likes-button").toggleClass(color);
}

$(document).ready(function() {
$(".likes-button").click(function() {
var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
var el = this;
var ajaxdata = $(this).attr("data-id");
var ajaxstring = $(this).attr("string");
console.log(ajaxstring);

$.ajax({
type: "POST",
url: "/ajax/upvote/",
data: JSON.stringify({ product_id: ajaxdata, string: ajaxstring }),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-CSRFToken": csrftoken
},

success: function(response) {
var up = response["likes"];
var string = response["string"];
console.log(string);
console.log(up);
$(el)
.find(".target")
.html(up);
$(el)
.find(".string")
.html(string);
if (Cookies.get("color")) {
$(".likes-button").toggleClass(Cookies.get("color"));
Cookies.remove("color");
} else {
Cookies.set("color", "heart");
$(".likes-button").toggleClass("heart");
}
},
error: function(rs, e) {
alert(rs.responseText);
}
});
});
});

关于javascript - 如何在第二次点击后销毁cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60017586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com