我得到a" ReferenceError:文档未定义"在尝试
时var body = document.getElementsByTagName("body")[0];
我之前在其他代码中看过这个并没有造成任何麻烦。为什么现在呢? 随之而来的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>
代码如下:
(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 i=0; i < questions.choices.length; i+=1) {
body.innerHTML(
"<input type=\"radio\" name=\"sex\" value=\"male\">"
+ questions.choices[i] + "<br>");
}
});
};
var q1 = new Question("What is red?", ["Color","Animal","Building"],1);
var q2 = new Question("Most popular music?", ["Latin","Pop","Rock"],2);
var quiz = new Quiz();
quiz.questions.push(q1);
quiz.questions.push(q2);
quiz.showAllQuestions();
})();
尝试此链接中的完整代码HERE
答案 0 :(得分:9)
这是因为我正在使用Next JS
,它具有服务器端渲染功能。使用服务器端渲染时,没有浏览器。因此,将没有任何变量window
或document
。因此,出现此错误。
解决:
如果使用的是Next JS,则可以使用动态渲染来防止组件的服务器端渲染。
import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
ssr: false
})
export default () => <DynamicComponentWithNoSSR />
如果您正在使用任何其他服务器端渲染库。然后在componentDidMount
中添加要在客户端运行的代码。如果您使用的是React Hooks,请使用useEffects
代替componentsDidMount
。
import React, {useState, useEffects} from 'react';
const DynamicComponentWithNoSSR = <>Some JSX</>
export default function App(){
[a,setA] = useState();
useEffect(() => {
setA(<DynamicComponentWithNoSSR/>)
});
return (<>{a}<>)
}
参考文献:
答案 1 :(得分:4)
这取决于自执行匿名函数的运行时间。它可能在定义window.document
之前运行。
在这种情况下,请尝试添加侦听器
window.addEventListener('load', yourFunction, false);
// ..... or
window.addEventListener('DOMContentLoaded', yourFunction, false);
yourFunction () {
// some ocde
}
更新(更新问题并包含代码后)
请阅读以下有关从插入的JavaScript引用DOM元素并在head
元素中运行的问题:
- “getElementsByTagName(…)[0]” is undefined?
- Traversing the DOM
答案 2 :(得分:3)
尝试在/ body标记之前添加脚本元素
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/quiz.css" />
</head>
<body>
<div id="divid">Next</div>
<script type="text/javascript" src="js/quiz.js"></script>
</body>
</html>
答案 3 :(得分:0)
尝试:window.document ......
var body = window.document.getElementsByTagName("body")[0];