如何将点击功能的启动切换保存为Cookie

时间:2019-03-02 14:24:15

标签: javascript html5 twitter-bootstrap cookies

如何将引导程序切换onclick函数保存为Cookie

我的html是:

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

,切换的javascript是:

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

我如何将切换项另存为Cookie,以便在更改切换项时,即使重新加载页面或移动到另一个页面并再次进入该页面,它仍保持这种状态。

1 个答案:

答案 0 :(得分: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