我使用以下代码来切换特定的 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">
1 回答
叮当猫咪
TA贡献1776条经验 获得超12个赞
使用 local 或 sessionStorage,则无需担心 cookie 是否正确
试试这个简化版
const checkBTW = function() {
const checked = $('#togglebtw').is(":checked");
$(".price-container .price-including-tax").toggle(!checked);
$(".price-container .price-excluding-tax").toggle(checked);
localStorage.setItem("togglebtw",checked?"true":"false");
};
$(function() {
$('#togglebtw')
.on("click",checkBTW)
.prop("checked",localStorage.getItem("togglebtw")==="true");
checkBTW();
});
添加回答
举报
0/150
提交
取消
