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?
曾经蜡笔没有小新2017-05-19 10:28:53
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>
PHPz2017-05-19 10:28:53
<!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
世界只因有你2017-05-19 10:28:53
<!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.
世界只因有你2017-05-19 10:28:53
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_u15822017-05-19 10:28:53
<!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>