js loading in html 01

I found such a thing in learning js today and wrote the following code:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>dom1</title>
<script type="text/javascript">

function fn(obj) {
alert(obj); -----------------Printing added later
obj.className="selected"; -----------------error position
}
</script>
<style>
.selected{
background-color: #ffee99;
}
</style>
</head>
<body>

<script type="text/javascript">
var obj=document.getElementById("i3");
alert(1);

</script>

<ul>
<li>item1</li>
<li>item2</li>
<li id="i3">item3</li>
<li>item4</li>
<li>item5</li>
</ul>
<a href="javascript:;" οnclick="fn(obj);">Current node</a>

</body>
</html>

I started operating in the google browser and kept reporting errors, showing that obj.className="selected";  this code was wrong, and I didn’t know what went wrong at the beginning. Later, I added a print menu to the program and found it in the head The obj in the label is printed as null. According to Java's thinking, it should not be null. I have assigned a value to obj in the body. Later, after searching for information on the Internet, I found that the browser has two characteristics when loading javascript: 1. Execute immediately after loading; 2. When executed, it will block the subsequent content of the page.

When the javascript in the body is executed, because the following content is blocked, the value of i3 cannot be found, causing the obj assignment to fail, so the browser will report an error;

Solution: Put the javascript code in the body directly after the a tag, or directly outside the html tag.

Write so much first, then write new learning experience later

Reference link: https://www.cnblogs.com/CBDoctor/p/3745246.html

 https://coolshell.cn/articles/9749.html



Guess you like

Origin blog.csdn.net/zpt912/article/details/79019039