html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/reg_log.css">
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/reg_log.js"></script>
</head>
<body>
<form role="form" action="" method="" id="form">
<h1>建筑自学网注册</h1>
<div class="form-group">
<label for="username">用户名:</label>
<input type="text" name="username" class="form-control" id="username" placeholder="请输入用户名" value="a" required="required">
</div>
</form>
</body>
</html>
js:
(function()
{
'use strict';
var form = $("#form"),
username = $("#username"),
usernameVal = username.val();
alert(usernameVal);
})()
显示:undefined
我把js和HTML文件都写在一起,发现可以弹出a
追问我刚才试了一下,js放在HTML页面,果然能取到;但是,这是为什么呢?
追答js里这样写可以
window.onload = function(){
'use strict';
var form = $("#form"),
username = $("#username"),
usernameVal = username.val();
alert(usernameVal);
}