如何将bootstrap切换onclick功能保存为cookie
我的HTML是:
<input type="checkbox" id="toggle-two"></p>
并且切换的javascript是:
<script>
$(function() {
$('#toggle-two').bootstrapToggle({
on: 'Received',
off: 'Not Received'
});
})
</script>
我如何将切换保存为cookie,以便当我更改切换时,即使重新加载页面或者如果我移动到另一个页面并再次访问该页面,它也会保持这样状态。
您将使用.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)
}
})