• 使用表单对象时,报错 form is undefine


    先看例子

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8" />
    		<title>hello</title>
    		<script src="js/myjs.js"></script>
    	</head>
    	<body>
    		<form name="form"> 
    			<input name="password" value="password" />
    			<input name="name" value = "name" />
    		</form>
    		
    	</body>
    </html>
    

     导入的js文件代码为

    function test(){
        
        var test = form.name.value;
        var test2 = form.password.value;
        console.log(test);
        console.log(test2);
    }
    test()

     报错信息如下:

     

     

     

    不采用动态导入,使用内联JS

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8" />
    		<title>hello</title>
    	</head>
    	<body>
    		<form name="form"> 
    			<input name="password" value="password" />
    			<input name="name" value = "name" />
    		</form>
    		<script>
    			function test(){
    				
    				var test = form.name.value;
    				var test2 = form.password.value;
    				console.log(test);
    				console.log(test2);
    			}
    			test()
    		</script>
    	</body>
    </html>
    

     运行正确,结果如下:

     

    移动内联js位置,

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8" />
    		<title>hello</title>
    		<script>
    			function test(){
    				
    				var test = form.name.value;
    				var test2 = form.password.value;
    				console.log(test);
    				console.log(test2);
    			}
    			test()
    		</script>
    	</head>
    	<body>
    		<form name="form"> 
    			<input name="password" value="password" />
    			<input name="name" value = "name" />
    		</form>
    	</body>
    </html>
    

     又报错

    原因:调用test()函数时,form对象还未生成,也可以这样子写

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8" />
    		<title>hello</title>
    		<script>
    			function test(){
    				
    				var test = form.name.value;
    				var test2 = form.password.value;
    				console.log(test);
    				console.log(test2);
    			}
    		</script>
    	</head>
    	<body>
    		<form name="form"> 
    			<input name="password" value="password" />
    			<input name="name" value = "name" />
    		</form>
    		<script>
    			test()
    		</script>
    	</body>
    </html>
    

     

  • 相关阅读:
    2019暑假——区域赛真题讲解
    2019暑假杭电训练赛(补题及笔记)
    2019暑假牛客训练赛(补题及笔记)
    网络流——最大流-Dinic算法
    SPFA
    K短路(A*+SPFA)
    从业务架构视角聊聊大型商业银行的转型实践
    互联网 40 岁失业是一个无法打破的魔咒吗
    Hadoop集群中出现的节点有哪些作用
    CDH集群的角色划分
  • 原文地址:https://www.cnblogs.com/xiaohaodeboke/p/12313141.html
Copyright © 2020-2023  润新知