Javascript代码未在浏览器中运行

时间:2015-02-28 17:14:48

标签: javascript html web

我有以下javascript代码,我正在尝试在Google Chrome和Internet Explorer上运行它,但两者都得到一个空白页面。我无法理解脚本中的错误是什么? 请告诉我它有什么问题。

<!DOCTYPE html>
<html>
    <head>
         <title>Changing Background Color</title>


    </head>

    <body>
        <script type= "text/javascript">
            document.write( "test run");
            var colors={"red","orange","green","blue","brown","purple","gray","white"}
            var index=0;
            function changecolor()
            {
                 for(index=0;colorindex<colors.length;index++)
                 {
                     document.bgcolor=colors[index];
                 }
            }
            function startchange()
            {
                setinterval("changecolor()",3000);
            }
            window.onload=startchange();
        </script>
    </body>

</html>

4 个答案:

答案 0 :(得分:1)

一个小错字,而不是bgcolor它应该是bgColor

希望它有所帮助.. :)

答案 1 :(得分:1)

一些拼写错误和语法错误,其中您使用错误类型的括号数组

var colors = ["red", "orange", "green", "blue", "brown", "purple", "gray", "white"], // array literal
    index = 0;
function changecolor() {
     for (index = 0; index < colors.length; ++index) { // fix typo
         document.bgColor = colors[index]; // typo
     }
     // are you sure you wanted this loop and not to do something like
     // document.bgColor = colors[++index % colors.length];
     // ?
}
function startchange() {
    setInterval(changecolor, 3000); // typo, pass function in directly
}
window.onload = startchange; // set function, not invoke function

此外,您的for循环将比人类看到的更快地应用更改,您确定要进行此行为吗?请参阅上面的评论,了解您的意图

答案 2 :(得分:1)

document.write()

会覆盖当前文档,因此您的所有JavaScript都会丢失。删除它,或改为使用alert()。

答案 3 :(得分:0)

您的代码存在一些语法问题。

首先,您需要从"中删除引号(())和setInterval并将I大写。

setInterval(changecolor, 3000);

setInterval函数有两个参数:一个回调函数(可以是一个局部变量,如changecolor函数)和一个数字(间隔的毫秒数)。

您还需要使用[]而不是{}正确声明您的数组。此外(尽管没有必要)在声明的末尾加上;

var colors = ["red", "orange", "green", "blue", "brown", "purple", "gray", "white"];

正如Tarun Gaba指出的那样,您应该使用bgColor代替bgcolor

相关问题