如何在点击功能上保存bootstrap切换作为cookie

问题描述 投票:0回答:1

如何将bootstrap切换onclick功能保存为cookie

我的HTML是:

<input type="checkbox" id="toggle-two"></p>

并且切换的javascript是:

    <script>
      $(function() {
        $('#toggle-two').bootstrapToggle({
          on: 'Received',
          off: 'Not Received'
        });
      })
    </script>

我如何将切换保存为cookie,以便当我更改切换时,即使重新加载页面或者如果我移动到另一个页面并再次访问该页面,它也会保持这样状态。

javascript html5 twitter-bootstrap cookies
1个回答
0
投票

您将使用.change函数与Javascript的自定义setCookie方法:

function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

$("#toggle-two").change(function(){
    if($(this).prop("checked")){
       //Set 'Received'
       setCookie('cookiename', 'Received', 7)
    }else{
       //Set 'Not Received'
       setCookie('cookiename', 'Not Received', 7)
    }
})

来源 - Set cookie and get cookie with JavaScript

© www.soinside.com 2019 - 2024. All rights reserved.