3 回答
TA贡献1802条经验 获得超6个赞
我已经重写了javascript。源文件中的文档。
window.onload = () => {
// Capture the header elements in an array
const hdr = [...document.querySelectorAll('header')];
// Add an eventlistener for each header element
hdr.map( (h) => {
h.addEventListener( "click", (e) => {
// Toggle the class for the next sibling (article)
const t = e.currentTarget.nextElementSibling;
t.classList.toggle("dsplyNne");
});
});
}
.dsplyNne {
display: none;
}
.crsr {
cursor: pointer;
}
.dsplyBlck {
display: block;
}
<section>
<header class='crsr'>
Header
</header>
<article class='dsplyNne'>
Details
</article>
</section>
<section>
<header class='crsr'>
Header
</header>
<article class='dsplyNne'>
Details
</article>
</section>
TA贡献1828条经验 获得超4个赞
解决方案:
function toggleElm(elem) {
let x = document.getElementById(elem);
if (x.classList.contains('dsplyBlck')) {
x.classList.add('dsplyNne');
x.classList.remove('dsplyBlck');
} else {
x.classList.add('dsplyBlck');
x.classList.remove('dsplyNne');
}
}
<html>
<head>
<style>
.dsplyNne{
display:none;
}
.crsr{
cursor:pointer;
}
.dsplyBlck{
display:block;
}
</style>
</head>
<body>
<section>
<header class='crsr' onclick="toggleElm('target1')">
Header
</header>
<article class='dsplyNne' id="target1">
Details
</article>
</section>
<section>
<header class='crsr' onclick="toggleElm('target2')">
Header
</header>
<article class='dsplyNne' id="target2">
Details
</article>
</section>
</body>
</html>
TA贡献2041条经验 获得超4个赞
您只需使用Element.classList.toggle('YOUR_CLASS')
( doc )来简化这些
window.onload = function() {
var hdr = document.querySelectorAll('header');
for (var i = 0; i < hdr.length; i++) {
hdr[i].onclick = function() {
var elm = this.closest('section').querySelector('article');
elm.classList.toggle('dsplyBlck');
}
}
}
<html>
<head>
<style>
.dsplyNne {
display: none;
}
.crsr {
cursor: pointer;
}
.dsplyBlck {
display: block;
}
</style>
</head>
<body>
<section>
<header class='crsr'>
Header
</header>
<article class='dsplyNne'>
Details
</article>
</section>
<section>
<header class='crsr'>
Header
</header>
<article class='dsplyNne'>
Details
</article>
</section>
</body>
</html>
添加回答
举报