【发布时间】:2015-03-16 21:28:15
【问题描述】:
当我在head 标签中声明脚本标签时,我的代码不起作用,例如:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.11.2.js" async></script>
<script type="text/javascript" src="skript.js" async></script>
</head>
<body>
<p>
Click "Try it" to execute the displayDate() function.
</p>
<button id="myBtn">
Try it
</button>
<p id="demo"></p>
</body>
</html>
但是当我在底部body 标记中设置脚本标记时,它可以工作,例如:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<p>
Click "Try it" to execute the displayDate() function.
</p>
<button id="myBtn">
Try it
</button>
<p id="demo"></p>
<script type="text/javascript" src="jquery-1.11.2.js" async></script>
<script type="text/javascript" src="skript.js" async></script>
</body>
</html>
脚本文件包含以下内容:
document.getElementById("myBtn").onclick = function(){displayDate()};
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
有人能准确回答为什么会这样吗?
【问题讨论】:
-
因为当元素在头部时,你在它存在之前引用它。
-
learn.jquery.com/using-jquery-core/document-ready 看看这个以获得进一步的解释。
-
那么如果我在脚本中引用一个标签,那么脚本标签必须在脚本中引用的标签之后?
-
原生 JavaScript 也有解决方案,像 jQuery 这样的完整库并不是解决这个“小”和普遍问题的正确答案
-
@DanielRuf 我并没有建议将其作为答案,但它确实提供了一些关于等待 dom 加载之前您可以对其进行操作的信息。
标签: javascript html tags