代码之家  ›  专栏  ›  技术社区  ›  Babiker

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

  •  2
  • Babiker  · 技术社区  · 14 年前

    我正在尝试附加到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 回复  |  直到 14 年前
        1
  •  2
  •   Nick Craver    14 年前

    你的 for 循环已关闭1:)

    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 它的财产。