我有一個login.js,它具有在按下HTML中的clickme按鈕時調用的函數。.js中的Javascript函數無法在.html中獲取ElementElementById
document.getElementById('clickMe').addEventListener('click',execuateAllCode);
下面的線是在由clickme按鈕調用的函數,它不工作
var password = document.getElementById("password").value;
它給這個錯誤:
Uncaught TypeError: Cannot read property 'value' of null
popup.html包含此代碼:
...
<input id="clickMe" type="button" value="clickMe"/>
<input type="password" name="password" id="password" value="temppassword" placeholder="Password"/>
...
The錯誤應該表示沒有包含id =「password」的元素。但我確實有這個ID。 login.js中的函數不能「看到」HTML文件中的輸入嗎?
編輯1: 我已嘗試添加:
window.onload = function() {
execuateAllCode()
};
到.js文件,但是這並沒有擺脫錯誤的,這也導致在代碼的其他部分錯誤,停止造型。
的HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<input id="clickMe" type="button" value="clickme"/>
<script language="javascript" src="login.js"></script>
<input type="text" name="email" id="username" value="[email protected]" placeholder="Email"/>
<input type="password" name="password" id="password" value="temppass" placeholder="Password"/>
</body>
</html>
login.js:
document.getElementById('clickMe').addEventListener('click',execuateAllCode);
function execuateAllCode() {
document.write("<br />" + "From login" + "<br />");
var output;
output = FunctionOne();
document.write("<br /> the output: " + output + "<br />");
}
function FunctionOne(){
...
var password = document.getElementById("password").value;
var user_name = document.getElementById("username").value;
...
}
這一切都取決於代碼的運行時間。如果代碼在構建DOM之前運行,那麼DOM中不會有這樣的元素。 – Pointy
**沒有包含id =「密碼」的元素** - 是,**或該特定元素的值爲空** - 否。 – Igor
運行密碼代碼,我可以看到並更改值,然後按下按鈕並調用帶有getelementbyid的代碼。 @Points – Rorschach