wwz1 2021-01-31 12:50 采纳率: 0%
浏览 28

关于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>

  • 写回答

2条回答 默认 最新

  • 天际的海浪 2021-01-31 16:13
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 寻找公式识别开发,自动识别整页文档、图像公式的软件
  • ¥15 为什么eclipse不能再下载了?
  • ¥15 编辑cmake lists 明明写了project项目名,但是还是报错怎么回事
  • ¥15 关于#计算机视觉#的问题:求一份高质量桥梁多病害数据集
  • ¥15 特定网页无法访问,已排除网页问题
  • ¥50 如何将脑的图像投影到颅骨上
  • ¥15 提问一个关于vscode相关的环境配置问题,就是输入中文但是显示不出来,代码在idea可以显示中文,但在vscode不行,不知道怎么配置环境
  • ¥15 netcore使用PuppeteerSharp截图
  • ¥20 这张图页头,页脚具体代码该怎么写?
  • ¥20 WPF MVVM模式 handycontrol 框架, hc:SearchBar 控件 Text="{Binding NavMenusKeyWords}" 绑定取不到值