gpt4 book ai didi

javascript - 引用错误 : document is not defined (in plain JavaScript)

转载 作者:可可西里 更新时间:2023-11-01 01:25:33 25 4
gpt4 key购买 nike

我在尝试

时收到“ReferenceError: document is not defined”
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

最佳答案

这发生在我身上,因为我正在使用具有服务器端渲染的 Next JS。当您使用服务器端渲染时,没有浏览器。因此,不会有任何变量 windowdocument。因此出现此错误。

解决办法:

如果您使用的是 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. https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
  2. https://reactjs.org/docs/hooks-effect.html

关于javascript - 引用错误 : document is not defined (in plain JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24647839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com