1

我正在构建这个小 cookiescript,它在单击按钮时创建一个 cookie,然后隐藏消息。

但是现在我正在构建函数以在看到 cookie 时隐藏消息(div#cookie),但我每次都会收到此错误,但我的 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/

4

1 回答 1

4

问题是您hidediv()在加载实际 HTML 内容之前调用了该函数。将脚本放在文档末尾(在结束body标记之前)或将其设置在window.onload/ on document ready

于 2012-08-03T09:22:23.543 回答