gpt4 book ai didi

javascript - 使用纯 Javascript 在 h1 标题点击上切换元素内容

转载 作者:行者123 更新时间:2023-11-28 09:05:15 25 4
gpt4 key购买 nike

我想在点击 h1 标题时切换一些内容。我希望能够单击 h1 标题并隐藏或显示其下的部分。

对于 Javascript,我试图选择所有 (5) 个部分,但不选择 h1,它们都在 aside 元素内。我也想不通。

请看看我的代码,让我知道你会做什么。

HTML

<aside>
<h1><a href="#">Title</a></h1>
<section>
<h1>Foo</h1>
<p>
Foo
</p>
</section>
<section>
<h1>Foo</h1>
<p>
Foo
</p>
</section>
<section>
<h1>Foo</h1>
<p>
Foo
</p>
</section>
<section>
<h1>Foo</h1>
<p>
Foo
</p>
</section>
<section>
<h1>Foo</h1>
<p>
Foo
</p>
</section>
</aside>

CSS

    .invisible {
display: none;
}

JS

// select
var laatste = document.querySelector('aside h1:not(:first-of-type)');

// hide
laatste.classList.add('invisible');

// toggle
document.querySelector('aside > h1').onclick = function() {
if (laatste.className === "invisible") {
laatste.classList.remove('invisible');
}
else {
laatste.classList.add('invisible');
}
}

我不允许使用 jQuery 并向我的 HTML 添加类或 div。

最佳答案

您可以选择所有 h1 header ,然后为每个 header 附加一个事件监听器。在点击事件中,您可以在您的部分内容元素上切换不可见类,在本例中为“

”。

JavaScript:

//select
var all_headers_list = document.querySelectorAll('aside section h1');

//toggle
for (i = 0; i < all_headers_list.length; ++i) {
var entry = all_headers_list[i];

entry.addEventListener('click', function(e) {
var header = e.target;

if (header.className === 'invisible_content') {
header.classList.remove('invisible_content');
showSectionContent(header.parentNode)
}else {
header.classList.add('invisible_content');
hideSectionContent(header.parentNode);
}
});
}

function hideSectionContent(section){
var section_content = section.querySelector('p');
if(section_content != undefined) section_content.classList.add('invisible');
}

function showSectionContent(section){
var section_content = section.querySelector('p');
if(section_content != undefined) section_content.classList.remove('invisible');
}

CSS:

.invisible_content {}

.invisible {
display: none;
}

请注意,在这种情况下,invisible_content 类只是作为隐藏内容的指示符。

示例: http://jsfiddle.net/4cqcL0Lg/

关于javascript - 使用纯 Javascript 在 h1 标题点击上切换元素内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26740776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com