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

lim*_*ker 19 javascript

尝试时,我得到一个"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 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();


        })();
Run Code Online (Sandbox Code Playgroud)

此处尝试此链接中的完整代码

Tes*_*ter 24

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

解决:

如果您使用 Next JS,您可以使用动态渲染来防止组件的服务器端渲染。

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
  ssr: false
})

export default () => <DynamicComponentWithNoSSR />
Run Code Online (Sandbox Code Playgroud)

如果您使用任何其他服务器端渲染库。然后将要在客户端运行的代码添加到componentDidMount. 如果您使用的阵营鱼钩,然后使用useEffects中的位置componentsDidMount

import React, {useState, useEffects} from 'react';

const DynamicComponentWithNoSSR = <>Some JSX</>

export default function App(){

[a,setA] = useState();
useEffect(() => {
    setA(<DynamicComponentWithNoSSR/>)
  });


return (<>{a}<>)
}
Run Code Online (Sandbox Code Playgroud)

参考 :

  1. https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
  2. https://reactjs.org/docs/hooks-effect.html


ero*_*man 8

这取决于自执行匿名函数何时运行。它有可能在window.document定义之前运行。

在这种情况下,请尝试添加侦听器

window.addEventListener('load', yourFunction, false);
// ..... or 
window.addEventListener('DOMContentLoaded', yourFunction, false);

yourFunction () {
  // some ocde

}
Run Code Online (Sandbox Code Playgroud)

更新:(在更新问题并包含代码之后)

阅读以下有关从插入并在head元素中运行的 JavaScript 引用 DOM 元素的问题:
- “getElementsByTagName(...)[0]” 未定义?
- 遍历 DOM

  • 在创建 DOM 之前,JS 可以运行某些实例(例如在插件中)。在发布时,无法检查完整代码。 (2认同)

Vin*_*t J 6

您可以停用整个组件的 ssr(检查 Trect 的答案),但它太过分了,因为您只需要在 ssr 中跳过一行。

您应该只检查是否document已定义(确定该函数是否被称为服务器端-无文档-或客户端-文档已定义-):

if (typeof document === 'undefined') {
    // during server evaluation
} else {
    // during client's browser evaluation
}
Run Code Online (Sandbox Code Playgroud)

就您而言,您不需要在服务器端执行任何操作,您可以执行以下操作:

var body = null;

if (typeof document !== 'undefined') {
    // will run in client's browser only
    body = document.getElementsByTagName("body")[0];
}
Run Code Online (Sandbox Code Playgroud)


小智 5

尝试像这样在 /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>
Run Code Online (Sandbox Code Playgroud)