我有这个JS脚本设置cookie并显示/隐藏div
<html>
<head>
<script type="text/javascript">
function setCookie (name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie (name) {
var cookie = " " + document.cookie;
var search = " " + name + "=";
var setStr = null;
var offset = 0;
var end = 0;
if (cookie.length > 0) {
offset = cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = cookie.indexOf(";", offset);
if (end == -1) {
end = cookie.length;
}
setStr = unescape(cookie.substring(offset, end));
}
}
if (setStr == 'false') {
setStr = false;
}
if (setStr == 'true') {
setStr = true;
}
if (setStr == 'null') {
setStr = null;
}
return(setStr);
}
function hidePopup() {
setCookie('popup_state', false);
document.getElementById('popup').style.display = 'none';
}
function showPopup() {
setCookie('popup_state', null);
document.getElementById('popup').style.display = 'block';
}
function checkPopup() {
if (getCookie('popup_state') == null) { // if popup was not closed
document.getElementById('popup').style.display = 'block';
}
}
</script>
</head>
<body onLoad="checkPopup();">
<a href="#" onClick="hidePopup(); return false;">Turn Off</a></br></br>
<a href="#" onClick="showPopup(); return false;">Turn On</a>
<div id="popup" style="display:none">Hello! Welcome to my site. If you want to hide this message then click</div>
</body>
</html>
我需要有人,如果有人能够向我解释,我该如何更改cookie值? (名称,过期等)以及如何将开/关按钮合并为1个按钮,以完成切换显示/隐藏和相应编辑cookie的工作。
答案 0 :(得分:1)
要更改cookie的当前值,您可以使用与cookie的当前值重叠的相同名称再次设置cookie
到第二个问题,您可以使用复选框打开/关闭
function shoWhidePopup(el){
if(el.checked==true){
showPopup();
}else if(el.checked==false){
hidePopup();
}
}
并在html中
<label>
<input type="checkbox" onclick="shoWhidePopup(this);" hidden>
<span style="appearance:button; -moz-appearance:button; -webkit-appearance:button;">show/hide</span>
</label>