首页 > Web开发 > 详细

关于js中onload事件的部分报错。

时间:2018-04-30 14:08:01      阅读:235      评论:0      收藏:0      [点我收藏+]
当使用onload获取元素时,建议在onload事件之前定义需要获取的元素名称,在onload里面只执行获取操作,这样获取到的元素在后面才能顺利使用。


<!
DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html" charset="UTF-8"> <title>有关form</title> </head> <script type="text/javascript"> var username; var myform; onload=function(){ username=document.getElementById("username"); myform=document.getElementById("myform"); } /*这样写会出现报错,myform变量写在onload里面,是个局部变量,执行表单提交的时候不能被调用到,应该要把执行表单提交的代码也放到onload里面。*/ myform.onsubmit=function(){ if(username.value=="name"){ return true; } return false; } </script> <body> <form action="" method="" id="myform" > 用户名:<input type="text" id="username"> <input type="submit" value="提交"> </form> </body> </html>


正确的方式
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html" charset="UTF-8">
    <title>有关form</title>
</head>
<script type="text/javascript">
    var username;
    var myform;
    onload=function(){
        username=document.getElementById("username");
        myform=document.getElementById("myform");
        myform.onsubmit=function(){
            if(username.value=="name"){
            return true;
            }
            return false;
        }
    }
    
</script>
<body>
<form action="" method="" id="myform" >
    用户名:<input type="text" id="username">
    <input type="submit" value="提交">
</form>
</body>
</html>

 

 

 

关于js中onload事件的部分报错。

原文:https://www.cnblogs.com/helloworldlx/p/8973493.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!