[英]Toggle the nearest content when click on anchor using jQuery
I have a content structure like this: 我有一个这样的内容结构:
<a href="#" class="toggle_button">Click me.</a>
<p class="hidden_content">This content is toggleable.</p>
<a href="#" class="toggle_button">Click me.</a>
<p class="hidden_content">This is a different section.</p>
<a href="#" class="toggle_button">Click me.</a>
<p class="hidden_content">This section is also different.</p>
I have already discovered how to make this work with one section, but how can I make it so that when I click on a toggle_button it opens only the nearest hidden_content class. 我已经发现了如何使这一部分有效,但是如何做到这一点,所以当我单击toggle_button时,它仅打开最近的hidden_content类。
$('a.toggle_button').click(function() {
$(this).next('p.hidden_content').toggle();
}
It's easy with JavaScript but you could also stay with plain CSS with the :target selector -- 使用JavaScript很容易,但是您也可以使用:target选择器来使用纯CSS-
<a href="#hiddenContent1" class="toggle_button">Click me.</a>
<p id="hiddenContent1" class="hidden_content">This content is toggleable.</p>
<style>
.hidden_content{
display:none;
}
.hidden_content:target{
display:block;
}
</style>
This will toggle the following div, and stop the page returning to the top: 这将切换以下div,并停止页面返回顶部:
$('a.toggle_button').click(function(e) {
e.preventDefault();
$(this).next('p.hidden_content').toggle();
}
Use the jQuery .next() selector 使用jQuery .next()选择器
$(".toggle_button").on("click", function () {
$(this).next(".hidden_content").toggle();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.