切换 div 并设置 cookie 以保存 jQuery

我使用以下代码来切换特定的 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">


皈依舞
浏览 131回答 1
1回答

叮当猫咪

使用 local 或 sessionStorage,则无需担心 cookie 是否正确试试这个简化版const checkBTW = function() {&nbsp; const checked = $('#togglebtw').is(":checked");&nbsp; $(".price-container .price-including-tax").toggle(!checked);&nbsp; $(".price-container .price-excluding-tax").toggle(checked);&nbsp; localStorage.setItem("togglebtw",checked?"true":"false");};$(function() {&nbsp; $('#togglebtw')&nbsp; &nbsp; .on("click",checkBTW)&nbsp; &nbsp; .prop("checked",localStorage.getItem("togglebtw")==="true");&nbsp;&nbsp; checkBTW();});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript