先看例子
<!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>