【问题标题】:javascript appending in a for loop not working but alering is附加在 for 循环中的 javascript 不起作用但警告是
【发布时间】:2010-06-21 00:34:26
【问题描述】:

我正在尝试在 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>

【问题讨论】:

  • 当你说“不能追加”时,这是什么意思?字符串还是空的?您可能想尝试在 cssText 上调用 toString(),尽管您不应该这样做。
  • 我可以做类似css += "somestring"; 这样的事情。

标签: javascript loops


【解决方案1】:

您的 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 属性时会导致错误。

【讨论】:

    猜你喜欢
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2021-08-15
    • 1970-01-01
    相关资源
    最近更新 更多