日期:2014-05-19  浏览次数:20550 次

关于javascript全局变量和局部变量访问的问题!!
自己写了一个简单的javascript代码,但是发现问题了,是关于全局变量和局部变量的!哪位热心的朋友可以帮忙解释一下啊?为什么声明了全局变量,反而在函数里得不到该变量的值,总提示"undefined",只能在函数里声明局部变量才可以呢?是访问顺序的问题?代码如下:
<html>
<head>
<script language="javascript">
var pub = "全局变量"
var v1 = parseInt(document.getElementById("number1").value) ;
function sayHello(){ 
alert("pub是" + pub + ",可以提示出来。");
}

function test(){
//v1 = parseInt(document.getElementById("number1").value) ;
alert(v1);
alert("v1也是全局变量,但是总提示没有定义。");
}
</script>
</head>
<!-- 在页面载入时执行 -->
<body onload="sayHello()">
<input type = 'text' name = 'number1' id = 'number1'><p>
<input type = 'button' name = 'button' id = 'button' value ='显示' onclick = "test()">
</body>
</html>


------解决方案--------------------
HTML code
<html>
<head>
<script language="javascript">
var pub = "全局变量"
var v1;
function sayHello(){
v1 = parseInt(document.getElementById("number1").value);  
alert("pub是" + pub + ",可以提示出来。");
}

function test(){
//v1 = parseInt(document.getElementById("number1").value) ;
alert(v1);
alert("v1也是全局变量,但是总提示没有定义。");
}    
</script>
</head>
<!-- 在页面载入时执行 -->
<body onload="sayHello()">
<input type = 'text' name = 'number1' id = 'number1'><p>
<input type = 'button' name = 'button' id = 'button' value ='显示' onclick = "test()">
</body>
</html>