• 使用表单对象时,报错 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>
    

     

  • 相关阅读:
    在tortoiseSVN上将trunk的代码merge到branch上去
    ajax提交后完全不进入action直接返回错误
    Eclipse "IOConsole updater" has encounter a problem
    jquery判断checkbox是否选中及改变checkbox状态[转]
    JS的Data类型格式化(转)
    Eclipse内置Tomcat的配置
    firebug下载时出现there was an error loading firebug
    Mac下Tomcat启动时乱码
    ibatis插入数据后返回自增长的主键
    给Mac下的iTerm2增加配色
  • 原文地址:https://www.cnblogs.com/xiaohaodeboke/p/12313141.html
Copyright © 2020-2023  润新知