关于js的window.onload属性

为什么以下程序运行会出现错?

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
			window.onload = function(){
				function showTime(){
						var time = new Date();
						time = time.toLocaleString();
						document.getElementById("sp_time").innerText = time;
					}
				window.setInterval('showTime()', 1000);
			}
		</script>
		<span id="sp_time" ></span>
	</body>
</html>

将window.onload属性去掉后则可以运行

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
			function showTime() {
				var time = new Date();
				time = time.toLocaleString();
				document.getElementById("sp_time").innerText = time;
			}
			window.setInterval('showTime()', 1000);
		</script>
		<span id="sp_time"></span>
	</body>
</html>

window.setInterval('showTime()', 1000); 中第一个参数是字符串'showTime()',这个字符串中的代码是在全局作用域中执行的。
而showTime()函数是在window.onload事件函数中定义的,在全局作用域中找不到。
 

需要把showTime()函数放在全局作用域中
        <script type="text/javascript">
            function showTime(){
                var time = new Date();
                time = time.toLocaleString();
                document.getElementById("sp_time").innerText = time;
            }
            window.onload = function(){
                window.setInterval('showTime()', 1000);
            }
        </script>
或者是setInterval中第一个参数改为函数的地址
            window.onload = function(){
                function showTime(){
                        var time = new Date();
                        time = time.toLocaleString();
                        document.getElementById("sp_time").innerText = time;
                    }
                window.setInterval(showTime, 1000);
            }