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