我有一个JavaScript函数,可以让我切换联系表单的可见性。表单提交后,我希望表单保持打开状态。是否有一些创建cookie的方法可以告诉脚本在提交后重新加载页面时显示表单。
HTML
<a href="#" onClick="toggle_visibility('toggle');">Contact</a>
CSS
#toggle{
display:none;
}
JS
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block'){
e.style.display = 'none';
}else{
e.style.display = 'block';
}
}
答案 0 :(得分:2)
您可以使用任何服务器端技术重定向到/ ThePage?toggle = 1并使用以下内容读取url参数:
function onload() {
var toggle = getUrlParams()["toggle"];
if (toggle == "1") toggle_visibility('toggle');
}
function getUrlParams() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
答案 1 :(得分:1)
您可以使用本地javascript(不涉及服务器)将状态保存在cookie中:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function toggle_visibility(id, cookieName) {
var e = document.getElementById(id);
var visible;
if(e.style.display == 'block') {
e.style.display = 'none';
visible = false;
} else {
e.style.display = 'block';
visible = true;
}
if (cookieName) {
createCookie(cookieName, visible, 1);
}
}
然后,当您加载页面时,您可以在加载DOM后通过调用此函数来恢复以前的状态:
function restore_visibility(id, cookieName) {
var visibility = readCookie(cookieName);
if (visibility == null) return; // no cookie
var e = document.getElementById(id);
if (visibility) {
e.style.display = 'block';
} else {
e.style.display = 'none';
}
}
您可以使用"contactFormVisible"
之类的字符串作为cookieName。