ReferenceError:未定义文档(在纯JavaScript中)

时间:2014-07-09 07:35:57

标签: javascript

我得到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

4 个答案:

答案 0 :(得分:9)

这是因为我正在使用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

答案 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];