本文介绍了DOM元素引用为null-未捕获的TypeError:无法读取null的属性"style"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个灵活的菜单,单击链接"时不需要在页面之间跳转.我为此使用的JavaScript如下:

I'm working on a flexible menu, that does not need to jump from page to page when clicking 'links'.The JavaScript I use for that is as follows:

var inbox = document.getElementById("u-content-inbox");
var friends = document.getElementById("u-content-friends");
var agenda = document.getElementById("u-content-agenda");
var list = document.getElementById("u-content-list");
var news = document.getElementById("u-content-news");
var notes = document.getElementById("u-content-notes");

function Inbox() {
  inbox.style.visibility='visible';
}

function Friends() {
  friends.style.visibility='visible';
}

function Agenda() {
  agenda.style.visibility='visible';
}

function List() {
  list.style.visibility='visible';
}

function News() {
  news.style.visibility='visible';
}

function Notes() {
  notes.style.visibility='visible';
}

div元素如下:

<div id="u-content-inbox" style="visibility:hidden;">
  Inbox
</div>

<div id="u-content-friends" style="visibility:hidden;">
  Friends
</div>

每个div都有一个"u-content-x".但是,当我尝试将样式属性可见性"更改为可见时.它给了我以下错误:未捕获的TypeError:无法读取null的属性'style'

Each div has a "u-content-x".However, when I try to change the style attribute "visibility" to visible. It gives me the following error: Uncaught TypeError: Cannot read property 'style' of null

我没看到我在做什么错.有人可以向我请准我为什么完全使用JavaScript,或者我无法使它正常工作吗?每当我进行检查

I'm not seeing what I'm doing wrong. Could somebody please bring clearance to me why exactly JavaScript, or rather, I fail to make it work?Whenever I run a check on

if(!inbox) {
alert("Inbox div has not been found);
}

不显示警报消息.

推荐答案

请确保在加载文档后调用JavaScript!我几乎可以肯定,您正在尝试在dom中存在元素引用之前获取它们.最佳做法是将所有脚本放在body标签关闭之前.

Make sure you call your javascript after the document is loaded! I'm nearly certain you are trying to get element references before they exist in the dom. The best practices is to put all scripts just before the closing of the body tag.

  <script src="some/path/to/file.js"></script>
</body>

如果脚本在元素之前出现在文档中,则可以将代码放入此加载事件函数中:

If your scripts appear in the document before the elements do, you can put your code inside of this load event function:

window.addEventListener('load', function() {
 //your code here
});

就像您对代码体系结构的说明一样,您可以将一个类附加到每个元素,然后执行以下操作:

Just as a note on your code architecture, you could attach a class to each element and then do this:

var toMakeVisible = document.getElementsByClassName('some-class');
for (var i=0; i<toMakeVisible; ++i) {
  var elem = toMakeVisible[i];
  elem.style.visibility = 'visible';
}

这篇关于DOM元素引用为null-未捕获的TypeError:无法读取null的属性"style"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 20:53