zoukankan      html  css  js  c++  java
  • 使用表单对象时,报错 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>
    

     

  • 相关阅读:
    软件工程作业3.28
    毕业论文管理系统建模图
    软件工程建模图作业
    酒店管理系统
    闪屏和功能引导页面代码编写
    Android算法编程代码
    3.28软件工程作业
    毕业论文管理系统
    图书管理系统建模图
    酒店预订系统故事
  • 原文地址:https://www.cnblogs.com/xiaohaodeboke/p/12313141.html
Copyright © 2011-2022 走看看