javascript附加在for循环中不起作用但是alering是

时间:2010-06-21 00:34:27

标签: javascript loops

我试图在for循环中追加一个字符串。我可以提醒每个值bieng循环但我不能出于某种原因追加:

<html>
    <head>
        <script type="text/javascript" language="javascript">
            function doIt(){
                    var styleSheet = document.styleSheets[0];
                    var css="";
                    for (i=0; i<=styleSheet.cssRules.length; i++)
                    {
                        css += styleSheet.cssRules[i].cssText;
                        //alert(styleSheet.cssRules[i].cssText); //WORKS
                    }
            }
        </script>
        <style type="text/css">
            .container{display:none;}
            .markup-container{color:#404040;}
            .title{text:decoration:underline;}
            .body{color:#000;}
        </style>
    </head>
    <body>
        <input type="button" id="button" onmousedown="doIt()">
        <div class="container">
            <div class="markup-container">
                <div class="title">This is a title with some markup</div>
                <div class="body">This is the body with some markup and it's longer ^^</div>
            </div>
        </div>
    </body>
</html>

1 个答案:

答案 0 :(得分:2)

你的for循环被一个人关闭:)

for (i=0; i<=styleSheet.cssRules.length; i++)
//should be:
for (i=0; i<styleSheet.cssRules.length; i++)

最后发生这种情况时:

styleSheet.cssRules[styleSheet.cssRules.length].cssText

你会收到一个错误,因为你已超过数组的长度,而styleSheet.cssRules[i]undefined,当你尝试访问.cssText时会出错它的财产。