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

当使用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>


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