javascript 未捕获的类型错误:无法读取未定义的属性“显示”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33511496/
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
Uncaught TypeError: Cannot read property 'display' of undefined
提问by Alexander Boman Skoug
I'm trying to show and hide several divs based on which button is clicked but nothing happens and in the Chrome Inspector I get the error: "Uncaught TypeError: Cannot read property 'display' of undefined"
我试图根据点击的按钮显示和隐藏几个 div,但没有任何反应,在 Chrome Inspector 中我收到错误:“未捕获的类型错误:无法读取未定义的属性‘显示’”
Thanks in advance!
提前致谢!
Triggers and block:
触发器和阻止:
echo '<button class="more" onClick="toggleLyrics()">Show lyrics <i class="fa fa-chevron-down"></i></button>';
echo '<div class="lyricsBox" style="display: block;"><pre>' . $row['lyrics'] .'</pre></div>';
Script:
脚本:
<script>
function toggleLyrics(){
var lyricsMore = document.getElementsByClassName('more');
var lyricsBox = document.getElementsByClassName("lyricsBox");
var displaySetting = lyricsBox.style.display;
if (displaySetting == 'block') {
lyricsBox.style.display = 'none';
}
else {
lyricsBox.style.display = 'block';
}
}
</script>
回答by Alexander Boman Skoug
getElementsByClassName
returns a collection that you access by index in order to get the DOM elements found.
getElementsByClassName
返回您通过索引访问的集合,以获取找到的 DOM 元素。
You can do this individually:
您可以单独执行此操作:
lyricsBox[0].style.display
or in a typical for
loop.
或者在一个典型的for
循环中。
Another option, if you only need the first element matched, is to use querySelector
instead.
另一种选择,如果您只需要匹配的第一个元素,则改为使用querySelector
。
var lyricsBox = document.querySelector(".lyricsBox");
This will return the first element matched by the CSS selector. It also has better browser support than .getElementsByClassName
.
这将返回 CSS 选择器匹配的第一个元素。它还比.getElementsByClassName
.
It has a counterpart .querySelectorAll()
that returns a collection as well.
它也有一个.querySelectorAll()
返回集合的对应物。
回答by towry
getElementsByClassName
return an element collection, you need first get the element from the collection.
getElementsByClassName
返回元素集合,首先需要从集合中获取元素。
function toggleLyrics(){
var lyricsMore = document.getElementsByClassName('more');
var lyricsBox = document.getElementsByClassName("lyricsBox");
var displaySetting = lyricsBox[0].style.display;
if (displaySetting == 'block') {
lyricsBox[0].style.display = 'none';
}
else {
lyricsBox[0].style.display = 'block';
}
}