出于某种原因,我遇到了这个问题:Uncaught TypeError:无法在document.getElementById行读取null的属性“value”。问题是什么?我不知道。
HTML代码:
<html>
<head>
<title>I am a chrome extension</title>
<link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />
<script src="scripts.js"></script>
</head>
<body bgcolor="#34495e">
<div class="login-card">
<h1>Please Enter Your Birthday</h1><br>
<form>
<input type="date" name="user" placeholder="Username">
<input type="submit" id="age" name="submit" class="login login-submit" value="Submit">
</form>
</div>
</body>
</html>
scripts.js
function getAge()
{
var age = document.getElementById("age").value;
console.log(age);
}
document.getElementById('age').onclick = getAge();
答案 0 :(得分:1)
在函数调用函数后使用括号。要将事件绑定到函数,只需引用getAge
而不括括号,如下所示:
document.getElementById('age').onclick = getAge;
您还应该确保等到使用onload事件完全加载DOM之后。您还应该花些时间仔细阅读properly bind javascript events。
答案 1 :(得分:1)
因为你将脚本包含在头部,并且它在dom元素之前加载。 您还需要应用pswg的答案。
解决这个问题的方法就是使用window.onload
window.onload = function () {
document.getElementById("age").onclick = getAge;
}
答案 2 :(得分:0)
这是因为在实际的html评估之前,你在头部包含了js文件。你不能getElementById因为元素还没有!
通常,js文件包含在底部,正好在结束体标记的上方。为确保使用document.onload();