Part of the error about the onload event in js.

When using onload to acquire elements, it is recommended to define the name of the element to be acquired before the onload event, and only perform the acquisition operation in onload, so that the acquired elements can be used successfully later. 


<!
DOCTYPE html > < html lang = "en" > < head > < meta http-equiv = "content-type" content = "text/html" charset = "UTF-8" > < title > about form </ title > </ head > < script type ="text/javascript" > var username; var myform; onload=function(){ username=document.getElementById("username"); myform=document.getElementById("myform"); } /* This will cause an error to be reported. The myform variable is written in onload and is a local variable. It cannot be called when executing form submission. The code that executes form submission should also be placed in 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>
 
 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325067321&siteId=291194637