根本不识别javaScript

时间:2016-06-05 12:33:38

标签: javascript html

我创建了一个简单的网页,因此我可以使用JavaScript。下面的代码是它的一小部分。我在其中写的javascript将不会做任何事情。我不知道为什么。我知道这不是一件难事,但我不知道它有什么问题。它就像浏览器根本无法识别脚本一样。有人可以帮我解决这个问题吗?

    <!DOCTYPE HTML>
    <html>
        <head>
            <meta charset="UTF-8" />
            <title>Add User</title>
            <link rel="shortcut icon" href="logo.png"/>
            <link rel="stylesheet" href="style.css" type="text/css"/>
            <script type="text/javascript">     
                function changeBackground() 
                {
                    alert("Java is working!");
                    document.getElementByID("top_nav").background-color = "green";
                    document.getElementByID("top_nav").innerHTML = "green";
                }
            </script>
        </head>
        <body>
        <div id="top_nav" onload="changeBackground()" style="height: 500px; width: 500px;">
<button type="button" onclick="changeBackground()">button</button>
</div>
        </body>
        </html>

2 个答案:

答案 0 :(得分:2)

没有div&#39; onload&#39;事件。您没有调用正确的函数(javascript区分大小写)来按ID获取元素,它的backgroundColor不是背景颜色,它不是样式对象,而是html元素本身。

此外,这是JavaScript。

<!DOCTYPE HTML>
    <html>
        <head>
            <meta charset="UTF-8" />
            <title>Add User</title>
            <link rel="shortcut icon" href="logo.png"/>
            <link rel="stylesheet" href="style.css" type="text/css"/>
            <script type="text/javascript">     
                function changeBackground() 
                {
                    alert("JavaScript is working!");
                    document.getElementById("top_nav").style.backgroundColor = "green";
                    document.getElementById("top_nav").innerHTML = "green";
                }
            </script>
        </head>
        <body>
        <div id="top_nav" style="height: 500px; width: 500px;">
<button type="button" onclick="changeBackground()">button</button>
</div>
        </body>
        </html>

答案 1 :(得分:-1)

应该是document.getElementById("top_nav").style.backgroundColorgetElementById,而不是getElementByID

   <!DOCTYPE HTML>
    <html>
        <head>
            <meta charset="UTF-8" />
            <title>Add User</title>
            <link rel="shortcut icon" href="logo.png"/>
            <link rel="stylesheet" href="style.css" type="text/css"/>
            <script type="text/javascript">     
                function changeBackground() 
                {
                    alert("Java is working!");
                    document.getElementById("top_nav").style.backgroundColor = "green";
                    document.getElementById("top_nav").innerHTML = "green";
                }
            </script>
        </head>
        <body>
        <div id="top_nav" onload="changeBackground()" style="height: 500px; width: 500px;">
<button type="button" onclick="changeBackground()">button</button>
</div>
        </body>
        </html>