Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

javascript - What's the difference between putting script in head and body?

I was getting a problem .

<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <script type="text/javascript">
  alert(document.getElementsByTagName("li").length); 
  </script>
  <title>purchase list</title>
</head>
<body>
  <h1>What to buy</h1>
  <ul id="purchases">
    <li> beans</li>
    <li>Cheese</li>
  </ul>
</body>

When I put scripts in head, the result shows 0

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
                      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Shopping list</title>
</head>
<body>
  <h1>What to buy</h1>

  <ul id="purchases">
    <li>Cheese</li> 
    <li>Milk</li>
    <script type="text/javascript">
    alert(document.getElementsByTagName("li").length);
    </script>
  </ul>
</body>

When I tried to put scripts in body, the result shows 2. why there is such a difference? what is the main difference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What's the difference between putting script in head and body?

The time that it runs.

When I put scripts in head, the result shows 0 Shopping list

The elements you are trying to access don't exist when the script runs (since they appear after the script in the document).

Note that you can write a script so that a function is called later (for various values of later including "when the entire document has loaded") using event handlers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...