为了账号安全,请及时绑定邮箱和手机立即绑定

切换 div 并设置 cookie 以保存 jQuery

切换 div 并设置 cookie 以保存 jQuery

皈依舞 2022-06-05 17:00:14
我使用以下代码来切换特定的 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();

});


查看完整回答
反对 回复 2022-06-05
  • 1 回答
  • 0 关注
  • 129 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号