zoukankan      html  css  js  c++  java
  • 关于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>
    
    
    
     
  • 相关阅读:
    一文搞定操作系统!超详细图文详解!请带着耐心点进来!
    一文搞定操作系统的进程和线程!
    别再敲代码了,用对工具,做可视化大屏原来这么简单!
    一个网站,让你拥有各类资源!!
    DCN v2
    SSD
    Pytorch 模型的加载与保存
    Pytorch分布式训练
    Pytorch中的BatchNorm
    OHEM(2)
  • 原文地址:https://www.cnblogs.com/helloworldlx/p/8973493.html
Copyright © 2011-2022 走看看