我使用以下代码来切换特定的 div 并使用 cookie 保存设置,以便它保留更改。
但由于某种原因,保存 cookie 部分无法正常工作。例如,使用以前的浏览器按钮时,似乎没有保存 cookie。
我在当前代码中缺少什么完美添加 cookie 并检查它。
function getCookieValue(a) {
var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
return b ? b.pop() : '';
}
$(document).ready(function() {
var redEl = $('input#togglebtw');
if (document.cookie.indexOf('togglebtw=') != -1) {
redEl.prop("checked", $.parseJSON(getCookieValue("togglebtw")));
}
if (redEl.prop("checked")) {
$(".price-container .price-including-tax").hide();
$(".price-container .price-excluding-tax").show();
} else {
$(".price-container .price-excluding-tax").hide();
$(".price-container .price-including-tax").show();
}
$('input#togglebtw').click(function() {
var expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + 31);
expiryDate = expiryDate.toUTCString();
if ($(this).attr("class") == "btwToggler") {
if (redEl.prop("checked")) {
$(".price-container .price-including-tax").hide();
$(".price-container .price-excluding-tax").show();
} else {
$(".price-container .price-excluding-tax").hide();
$(".price-container .price-including-tax").show();
}
document.cookie = "togglebtw=" + this.checked.toString() + "; expires=" + expiryDate;
}
});
});
<input id="togglebtw" class="btwToggler" type="checkbox">
叮当猫咪
相关分类