добавление JavaScript в цикл for не работает, но оповещение - PullRequest
2 голосов
/ 21 июня 2010

Я пытаюсь добавить строку в цикл 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 Ответ

2 голосов
/ 21 июня 2010

Ваш 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 для него.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...