为什么没我把window.onload=function{}就可以正常运行,不去就不能运行呢?

wulishengtian 2016-06-22 07:32:51
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<!--<link type="text/css" href="../Mycss/mcss2.css" rel="stylesheet">-->
<style type="text/css">
.init{background: #f5f5f5;font-weight:bold;font-size: 10px;color:#000000;}

#img1{width: 15px;height:15px;display: none;}

#img2{width: 15px;height:15px;display: none;}

.wrong{background: #f5f5f5;font-weight:bold;border:1px #ff0000 solid;color:#000000;}

.right{background: #f5f5f5;font-weight:bold;border:1px #00ff00 solid;color:#000000;}
</style>

<script type="text/javascript">
//window.onload=function() {
function validateEmail() {
var oImg1=document.getElementById("img1");
var oImg2=document.getElementById("img2");
var oIpt=document.getElementById("ipt1");
if(/^\w+@\w+\.\w+$/.test(oIpt.value)){
oIpt.className='right';
oImg2.style.cssText='display:inline-block';
oImg1.style.cssText='display:none';
return true;
} else {
oIpt.className='wrong';
oImg1.style.cssText='display:inline-block';
oImg2.style.cssText='display:none';
return false;
}
}
function validate() {
return validateEmail();
}
//}
</script>
</head>
<body>
<form id="myform" action='show.html' method='post' onsubmit="return validate()">
<div>
请输入常用邮箱地址:
<input type="text" id="ipt1" name="ipt1" class="init" onblur="validateEmail()">
<img id="img1" src="D:/Documents/Pictures/source material image/a.jpg"/>
<img id="img2" src="D:/Documents/Pictures/source material image/c.png"/>
</div>
<br>
<button type="submit">干嘛</button>
</form>
</body>
</html>
...全文
245 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
cocotsau 2016-06-22
  • 打赏
  • 举报
回复
变量、函数作用域的关系

window.onload = function(){
//匿名函数内部定义的变量为局部变量,函数为局部函数,外部无法访问
}

<form id="myform" action='show.html' method='post' onsubmit="return validate()">
<!--这里,在window.onload外部(全局环境)调用validate,自然无效,提示validate未定义-->
Go 旅城通票 2016-06-22
  • 打赏
  • 举报
回复
引用 2 楼 u013116426 的回复:
window.onload本身是加载事件,里面是用来调用方法执行方法的,你把方法写在里面是访问不到的
+++ 写到window.onload里面只能在window.onload里面可以访问,dom中配置的onclick调用的函数需要是window作用域下的
___紫菜 2016-06-22
  • 打赏
  • 举报
回复
window.onload本身是加载事件,里面是用来调用方法执行方法的,你把方法写在里面是访问不到的
usecf 2016-06-22
  • 打赏
  • 举报
回复
不注释也可以运行,不知道你那报什么错误

87,904

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧