当使用 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>
来源: http://www.bubuko.com/infodetail-2581278.html