可能的原因是什么document.getElementById,$("#id")或者任何其他DOM方法/ jQuery选择器没有找到元素?
示例问题包括:
.val(),.html(),.text())返回undefined返回的标准DOM方法null导致以下任何错误:
未捕获的TypeError:无法设置null的属性'...'未捕获的TypeError:无法读取null的属性'...'
最常见的形式是:
未捕获的TypeError:无法设置null的属性'onclick'
未捕获的TypeError:无法读取null的属性"addEventListener"
未捕获的TypeError:无法读取null的属性'style'
我正在尝试使用getElementById()获取元素,但即使元素存在,它也会返回null.我究竟做错了什么?
<html>
<head>
<title>blah</title>
<script type="text/javascript">
alert(document.getElementById("abc"));
</script>
</head>
<body>
<div id="abc">
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
尝试时,我得到一个"ReferenceError:文档未定义"
var body = document.getElementsByTagName("body")[0];
Run Code Online (Sandbox Code Playgroud)
我之前在其他代码中看过这个,并没有造成任何麻烦.为什么现在呢?随之而来的HTML页面只是体内的一个div.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/quiz.css" />
<script type="text/javascript" src="js/quiz.js"></script>
</head>
<body>
<div id="divid">Next</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
代码如下:
(function(){
var body = document.getElementsByTagName("body")[0];
function Question(question, choices, correctAns) {
this.question = question;
this.choices = choices;
this.correctAns = correctAns;
}
Question.prototype.checkAns = function(givenAns){
if (this.correctAns === givenAns) {
console.log("OK");
}
};
function Quiz() {
this.questions = [];
}
Quiz.prototype.showAllQuestions = function(){
this.questions.forEach(function(questions){
console.log(questions.question);
});
};
Quiz.prototype.showQuiz = function(){
this.questions.forEach(function(questions){
for (var …Run Code Online (Sandbox Code Playgroud)