我是新来的Java脚本。我正在练习代码。当我将代码放在头部分时,然后我得到了元素null,并且当我把它放在body中,但在元素之前,那么我也会得到null,但是如果我把它放在body中,但是在元素之后然后我得到元素。我想问问,为什么我在前两种情况下变得空了。这里是我的代码何时何地把javascript放在html中
<!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>
下面是我的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
而且还告诉我,把<script type="text/javascript" src="js/attributes.js"></script>
的一个元素后,同样是因为我写脚本标签中的脚本,如
<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>
这两件事是否意味着相同?
感谢
我想问一下当我们使用'
'。这和我们写'window.onload = someFunction(){...};'是一样的。就像我在.js文件中写入一个简单的函数,'function someFunction(){..}',然后在我的HTML中使用'',那么它与我包含的效果相同我的.js文件在头部分和那个.js我写'window.onload = someFunction(){...};'。两者是相同的? – Basit 2012-02-09 10:55:21这几乎是一样的。在html中设置为属性的
就像是说'window.onload = function(){something}',也就是说,放入属性的代码不必调用函数,它有一个隐含的函数。许多人不喜欢将他们的JavaScript混合到他们的HTML中,因为它可能更令人头疼。注意:你将要在JavaScript属性中设置引号。 – nnnnnn 2012-02-09 10:58:59