javascript - I just started learning JS and I encountered a small problem to solve.
黄舟
黄舟 2017-05-19 10:26:53
0
5
561
HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Blog</title>
    <script type="text/javascript" src="scripts/abc.js"></script>
</head>
<body>
    <p id="box">id</p>
</body>
</html>

JS code:
alert(document.getElementById("box").innerHTML);

Why can’t the above code be executed? There is no pop-up window when running it in Firefox browser. Any solution?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(5)
曾经蜡笔没有小新

Dear, your js files should be placed below, the loading order is wrong

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Blog</title>
</head>
<body>
    <p id="box">id</p>
     <script type="text/javascript" src="scripts/abc.js"></script>
</body>
</html>
PHPzhong
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Blog</title>
    <script type="text/javascript" src="scripts/abc.js"></script>
</head>
<body>
    <p id="box">id</p>
</body>
<script>
    alert(document.getElementById("box").innerHTML);
</script>
</html>

Because your code is not fully written, I guess you wrote the loading order in reverse

Execution timing
window.load look at this

世界只因有你
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Blog</title>
    <script type="text/javascript" src="scripts/abc.js"></script>
</head>
<body>
    <p id="box">id</p>
    <script>
        alert(document.getElementById("box").innerHTML);
    </script>
</body>
</html>

Personally test that this code can pop up a window in Firefox. It's possible that your firefox prevents alert boxes from popping up.
Switch to console.log(document.getElementById("box").innerHTML) f12 to view the console output.

Yes, as the previous brother said, your js comes in src before the body code. There was no dom at that time, so the node id=box cannot be obtained. This will report an error. One thing that those who learn js must know is to open the browser console to see if there is an error.

世界只因有你

Did you write alert in abc.js? If this is the case, the element with id="box" cannot be obtained when alert is executed

phpcn_u1582
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Blog</title>
    <script type="text/javascript">
    function test(){
        alert(document.getElementById("box").innerHTML);
    };
    window.onload=test;
    </script>
</head>
<body>
    <p id="box">id</p>
</body>
</html>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!