javascript JS 错误信息 textContent 设置为 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29843397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:10:40  来源:igfitidea点击:

JS error message textContent set as null

javascript

提问by Cam C

I am fairly new to JS and the world of web development, so apologise in advance if my question is a bit tedious.

我对 JS 和 Web 开发世界还很陌生,所以如果我的问题有点乏味,请提前道歉。

I wrote this code:

我写了这段代码:

var breakfast = new Object();
breakfast.food = "croissant";
breakfast.extra = ["mushroom", "cheese"];
breakfast.eat = function(){return this.food + " with " +  this.extra[0];}
var elBreakfast = document.getElementById("breakf");
elBreakfast.textContent = breakfast.eat();

I get an error message from the browser:

我从浏览器收到一条错误消息:

"Uncaught TypeError: Cannot set property 'textContent' of null"... 

What have I done wrong?

我做错了什么?

Thanks!

谢谢!

回答by jAndy

The only important code here is document.getElementById("breakf");. It seems like your browser is unable to query for the element with an ID of breakfwithin your HTML markup.

这里唯一重要的代码是document.getElementById("breakf");. 您的浏览器似乎无法breakf在您的 HTML 标记中查询 ID 为 的元素。

So you need to check your HTML code live in your browser. Check if there is any HTML node with id=breakf. If not, you correctly should receive that error.

因此,您需要在浏览器中实时检查 HTML 代码。检查是否有任何带有id=breakf. 如果没有,您应该正确地收到该错误。

回答by Bhanuprathap Bussa

Try to add script reference end of body tag in html page so that it will load breakf element and then applies the breakfast.eat();

尝试在 html 页面中添加 body 标签的脚本引用结束,以便它加载 breakf 元素,然后应用早餐.eat();

回答by Lilian Tedone

The error is coming from document.getElementById("breakf")here. The browser can't seem to find a node with an id of breakf.

错误来自document.getElementById("breakf")这里。浏览器似乎无法找到 ID 为 的节点breakf

Check your html code for a node with id="breakf", if it's not there, add it to the node you want to write text in and it should be good.

检查带有 的节点的 html 代码id="breakf",如果它不存在,请将其添加到要写入文本的节点,它应该很好。