我是Java脚本的新手.我正在练习code.When我把我的代码放在head部分,然后我得到元素null,当我把它放在body中,但在元素之前,然后我也得到null,但如果我把它放在body中,但是在元素之后然后我得到了元素.我想问一下为什么在前两种情况下我得到null.这是我的代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/attributes.js"></script> // null
</head>
<body>
<script type="text/javascript" src="js/attributes.js"></script> // null
<a id="braingialink"
onclick="return showAttributes();"
href="http://www.braingia.org" >Steve Suehring's Web Site
</a>
<script type="text/javascript" src="js/attributes.js"></script> // ok
</body>
Run Code Online (Sandbox Code Playgroud)
这是我的javascript
var a1 = document.getElementById("braingialink"); //get null in first two cases
window.alert(a1.getAttribute("href"));
a1.setAttribute("href", "www.google.com");
window.alert(a1.getAttribute("href"));
function showAttributes() {
var e = document.getElementById("braingialink");
var elementList = "";
for (var element in e) {
/**
* Sometimes, especially when first programming with JavaScript, you might not know what
* attributes are available for a given element. But you don’t have to worry about that, because
* of a loop that calls the getAttribute() method.
*/
var attrib = e.getAttribute(element);
elementList = elementList + element + ": " + attrib + "\n";
} //end of for()
alert(elementList);
} //end of function showAttributes
Run Code Online (Sandbox Code Playgroud)
并告诉我,放置 <script type="text/javascript" src="js/attributes.js"></script>
在a元素之后,就像我在脚本标签中编写脚本一样
<a href="http://www.braingia.org" id="braingialink">Steve Suehring's Web Site</a>
<script type="text/javascript">
var a1 = document.getElementById("braingialink");
alert(a1.getAttribute("href"));
a1.setAttribute("href","http://www.microsoft.com");
alert(a1.getAttribute("href"));
</script>
Run Code Online (Sandbox Code Playgroud)
这两件事情的意思是一样的吗?
谢谢
浏览器从上到下解析文档,如果它遇到一个<script>块(无论是内联脚本还是包含外部JS文件),它会在解析任何更多文档之前运行该JavaScript.如果该特定代码块试图引用任何元素,则它只能访问源中的那些元素,即已经解析的元素.
如果没有找到您提供的id的元素,则该document.getElementById()方法返回null,因此如果您尝试使用它来访问源中它下面的元素,则它们尚未被解析且无法找到.
处理这个问题的两种最常见的做法是:
将所有脚本放在底部,<body>这样当运行时,所有元素都将被解析.
创建一个"onload"处理程序,即定义一个在文档完成加载后立即运行的函数.您可以从<head>- 脚本块中执行此操作- 定义 onload函数的JavaScript 立即运行,但随后在所有内容加载后执行该函数.
以下是选项2的最简单方法:
window.onload = function() {
var x = document.getElementById("x");
// other element manipulation here
};
Run Code Online (Sandbox Code Playgroud)
没有什么能阻止你在同一个文档中做1 和 2,同时在文档<script>的中间抛出一些块,但是大多数人发现将它们的所有代码保存在一个位置更整洁.
| 归档时间: |
|
| 查看次数: |
4517 次 |
| 最近记录: |