日期:2014-05-16  浏览次数:20363 次

新手,有个问题想不明白!

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
var closeObj=document.getElementById("gc");
var floatObj=document.getElementById("gc");
function test(){
alert(closeObj);
alert(floatObj);
}
</script>
</head>
<body>
<div id="tc"><img src="images/2.jpg"/></div>
<div id="gc" onclick="test()"><img src="images/1-1.bmp"/></div>
</body>
</html>

上面这段代码,为什么当我单击下面的div的时候,会弹出两个null ,应该是返回两个div元素才对呀,javascript的代码到底是按什么顺序执行的?难道不是一行一行的解释下去的吗?哪位大神能够仔细的说清楚这个问题啊?

------解决方案--------------------

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
//正因为是一行一行的解释下去的,
你在这里getElementById("gc")定义closeObj和floatObj是错误的:
因为此时<div id="gc"还没加载呢!

var closeObj=document.getElementById("gc");
var floatObj=document.getElementById("gc");
function test(){
alert(closeObj);
alert(floatObj);
}
</script>
</head>
<body>
<div id="tc"><img src="images/2.jpg"/></div>
<div id="gc" onclick="test()"><img src="images/1-1.bmp"/></div>
</body>
</html>
你可以把上面的JS脚本放到后面

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="tc"><img src="images/2.jpg"/></div>
<div id="gc" onclick="test()"><img src="images/1-1.bmp"/></div>
</body>
</html>
<script type="text/javascript">
window.onload=function(){
  var closeObj=document.getElementById("gc");
  var floatObj=document.getElementById("gc");

function test(){
alert(closeObj);
alert(floatObj);
}
</script>

也可以在页面加载完成的函数里定义控件变量

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
window.onload=function(){
  closeObj=document.getElementById("gc");//注意:此处定义不要用var,要定义为全局变量