我的CS老師堅持說所有的JS都必須放在<head>
標籤和其他地方。他還堅持我們只使用香草JavaScript而沒有任何庫。所以爲了遵守,我創建了下面的表單,附帶JS來驗證它。問題是,當在狀態改變檢查器中包裝它不起作用。我的代碼如下DOM Ready vanilla javascript does not working
HTML
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body align="center">
<h2>Super Secret Login</h2>
<!--Added an onsubmit action to catch the form in case it isn't valid !-->
<form onsubmit="return j.validate()" name="myForm" action="http://sophist.cs.slcc.edu/~philn/cgi-bin/quick.cgi" method="post">UserID:
<input name="userid" size="15" /> <!-- Remember closing tags on all elements !-->
<br />
<br />Password:
<input name="password" size="15" />
<br />
<br />
<center>
<table cellspacing="20px">
<tr>
<td align="left">
<input id="submit" type="submit" value="Submit" />
</td>
<td align="right">
<input type="reset" value="Clear" />
</td>
</tr>
</table>
</center>
</form>
</body>
</html>
的JavaScript
function domReady() {
var flag;
var userid = document.myForm.userid;
var pas = document.myForm.password;
this.validate = function() {
if (userid.value === "milton1" && pas.value === "k1mb3r")
{
flag = 1;
} else if (userid.value === "shelly15" && pas === "4ng21") {
flag = 1;
} else {
flag = 0;
}
if (flag === 0) {
alert('There was a problem with your username and password');
return false;
} else {
return true;
}
};
}
// Mozilla, Opera, Webkit
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function() {
document.removeEventListener("DOMContentLoaded", arguments.callee, false);
var j = new domReady();
}, false);
// If IE event model is used
} else if (document.attachEvent) {
// ensure firing before onload
document.attachEvent("onreadystatechange", function() {
if (document.readyState === "complete") {
document.detachEvent("onreadystatechange", arguments.callee);
var j = new domReady();
}
});
}
現在沒有一個函數包裝了整個事情,並要求提交,因爲這工作的方法,只要我把劇本在頁面底部。有人能幫助我理解爲什麼它不能以這種方式工作嗎?
你的CS老師不是傻瓜 – NimChimpsky
人仍然使用上形成透明按鈕?不管什麼? –
最佳做法是腳本標記位於頁面的末尾以確保DOM已加載?回顧我對CS老師的個人看法,對這個問題有何看法? – richbai90