[英]Question regarding collapsable content with html/css/js
I've been looking around on some collapsables, most of them seem to use some extra code that doesn't seem to be needed or I can't understand haha.我一直在寻找一些可折叠的东西,其中大多数似乎使用了一些似乎不需要或我无法理解的额外代码哈哈。 anyways, I made a super simple one and in my mind and logic it SHOULD work.
无论如何,我做了一个超级简单的,在我的脑海和逻辑中它应该工作。 but apparently it gets the error of
但显然它得到了错误
app.js:4 Uncaught TypeError: Cannot read property 'style' of null
at btn (app.js:4)
at HTMLButtonElement.onclick (index.html:9)
if someone would be so kind to properly explain to me WHY this isn't working so I might understand the logic better?如果有人愿意向我正确解释为什么这不起作用,那么我可能会更好地理解逻辑? here is snippet:
这是片段:
var content = document.querySelector(".content"); function btn(){ if (content.style.display === "none") { content.style.display = "block"; } else { content.style.display = "block"; } }
.content { display: none; overflow: hidden; color: red; }
<button type="button" onClick="btn();">collapsible</button> <div class="content"> <p> inner content bla bla bla</p> </div>
Thanks in advance!提前致谢! /Thuse
/因此
As you have assigned a class name to that element so use querySelector instead of ID selector:由于您已为该元素分配了类名,因此请使用 querySelector 而不是 ID 选择器:
var content = document.querySelector(".content");
Please note that querySelectot returns the first occurance of a query.请注意 querySelectot 返回查询的第一次出现。 So if you have multiple elements you will need
(querySelectorAll(".blah"))[x]
to select the Xth element.因此,如果您有多个元素,则需要
(querySelectorAll(".blah"))[x]
来选择第(querySelectorAll(".blah"))[x]
个元素。
As a JQuery fan, using JQuery you just need 1 line of code:作为一个 JQuery 爱好者,使用 JQuery 你只需要 1 行代码:
function btn(){
$(".content").toggle()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.