Javascript 无法设置未定义的属性“显示”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12194435/
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
Cannot set property 'display' of undefined
提问by TikTaZ
I'm writting script to hide/show menu but I get some troubles.
我正在编写脚本来隐藏/显示菜单,但我遇到了一些麻烦。
function displayMenu() {
//var classMenu = event.target.className;
//classMenu += 'Menu';
//document.getElementsByClassName(classMenu).style.display = 'block';
document.getElementsByClassName('btn-pageMenu').style.display = 'block';
}
In comment what I want to do finally, but even if I try with static var it's not working. In the CSS :
在评论我最后想要做什么,但即使我尝试使用静态 var 它也不起作用。在 CSS 中:
fieldset.toolsbox ul.btn-pageMenu {display:none;}
I try like this too :
我也这样尝试:
.btn-pageMenu {display:none;}
No more success. Anybody have a suggestion ? I'm learning JS and I not finding errors when I compare with other similar scripts.
没有更多的成功。有人有建议吗?我正在学习 JS,并且在与其他类似脚本进行比较时没有发现错误。
Thanks for your help :)
谢谢你的帮助 :)
回答by KooiInc
document.getElementsByClassName('btn-pageMenu')
delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display
(if it's the first element from that list you want to change.
document.getElementsByClassName('btn-pageMenu')
提供一个nodeList。您应该使用:(document.getElementsByClassName('btn-pageMenu')[0].style.display
如果它是您要更改的列表中的第一个元素。
If you want to change style.display
for all nodes loop through the list:
如果要更改style.display
所有节点循环遍历列表:
var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
elems[i].style.display = 'block';
}
to be complete: if you use jquery it is as simple as:
完整:如果您使用jquery,它就像:
?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????
回答by HarleySG
I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.
我在网站https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/ 中找到了这个答案。
In this code we add multiple styles in an element:
在这段代码中,我们在一个元素中添加了多种样式:
let
element = document.querySelector('span')
, cssStyle = (el, styles) => {
for (var property in styles) {
el.style[property] = styles[property];
}
}
;
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
span{
font-family: sans-serif;
color: #323232;
background: #fff;
}
<span>
lorem ipsum
</span>