将脚本放在头部和身体之间有什么区别? [英] What's the difference between putting script in head and body?
问题描述
< head>
< meta http-equiv =content-typecontent =text / html; charset = utf-8/>
< script type =text / javascript>
alert(document.getElementsByTagName(li)。length);
< / script>
< title>购买清单< /标题>
< / head>
< body>
< h1>购买什么< / h1>
< ul id =purchases>
< li>豆< /锂>
< li>奶酪< / li>
< / ul>
< / body>
当我将脚本放在头部时,结果显示为0
<!DOCTYPE html PUBLIC - // W3C // DTD XHTML 1.1 // EN
< head>
http:// www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">
< meta http-equiv =content-typecontent =text / html; charset = utf-8/>
< title>购物清单< /标题>
< / head>
< body>
< h1>购买什么< / h1>
< ul id =purchases>
< li>奶酪< / li>
< li>牛奶< / li>
< script type =text / javascript>
alert(document.getElementsByTagName(li)。length);
< / script>
< / ul>
< / body>
当我尝试将脚本放入正文中时,结果显示为2.为什么会有这种差异?
主要区别是什么?
和身体?
运行时间。
当我将脚本放在头部时,结果显示0 Shopping list
您试图访问的元素不会存在于脚本运行时(因为它们出现在文档中的脚本之后)。
请注意,您可以编写脚本,以便函数稍后称为 / em>(对于以后的各种值,包括当整个文档加载时),使用事件处理程序。
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?
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.
这篇关于将脚本放在头部和身体之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!