我正在构建这个小的cookiescript,当单击按钮然后隐藏消息时会创建一个cookie。
但是现在我正在构建函数来隐藏消息(div#cookie)当cookie已经被seet,但我每次都会收到此错误,但我的div存在:
Uncaught TypeError: Cannot read property 'style' of null
现在这些是我正在使用的脚本,有人可以帮忙吗? :)
<script type="text/javascript">
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 eraseCookie(name) {
createCookie(name,"",-1);
}
</script>
这就是'hidediv'给出错误的地方,但点击按钮时确实有效:
<script type="text/javascript">
function hidediv() {
if (document.getElementById) {
document.getElementById('cookie').style.visibility = 'hidden';
createCookie('uscnCookieScriptJS','uscninternetservicescookiescriptjavascriptversion',365)
}
else {
if (document.layers) {
document.hideShow.visibility = 'hidden';
createCookie('uscnCookieScriptJS','uscninternetservicescookiescriptjavascriptversion',356)
}
else {
document.all.hideShow.style.visibility = 'hidden';
createCookie('uscnCookieScriptJS','uscninternetservicescookiescriptjavascriptversion',356)
}
}
}
function showdiv() {
if (document.getElementById) {
document.getElementById('cookie').style.visibility = 'visible';
}
else {
if (document.layers) {
document.hideShow.visibility = 'visible';
}
else {
document.all.hideShow.style.visibility = 'visible';
}
}
}
</script>
<script type="text/javascript">
if (document.cookie.indexOf("uscnCookieScriptJS") >= 0) {
alert("yes");
hidediv();
}
else {
alert("no");
}
</script>
可在此处找到该脚本:http://dev.uscn.nl/cookiescript/v2/
答案 0 :(得分:4)
问题是您在加载实际HTML内容之前调用hidediv()
函数。将脚本放在文档的末尾(在关闭body
标记之前)或将其设置为window.onload
/ on ready ready