I have an .content with 'many' div's inside:
<div class="content">
<div class="news">
<a class="show_more" href="#">show news 1</a>
<div class="hidden">
<p>some news 1</p>
<a class="close_hidden" href="#">close</a>
</div>
</div>
<div class="news">
<a class="show_more" href="#">show news 2</a>
<div class="hidden">
<p>some news 2</p>
<a class="close_hidden" href="#">close</a>
</div>
</div>
...
<div class="news">
<a class="show_more" href="#">show news n</a>
<div class="hidden">
<p>some news n</p>
<a class="close_hidden" href="#">close</a>
</div>
</div>
simple css: .hidden{display:none;}
and jQuery:
$(document).ready(function(){
$('.show_more').click(function(){
$('.hidden').slideDown();
});
$('.close_hidden').click(function(){
$('.hidden').slideUp();
});});
For obvious reasons, my code opens all the hidden divs, even when I click only one <a>
.
How to show hidden content by using $(this) or something similar?
I know it's possible by using <a>
id (adding to .class name id of tag <a>
):
$('.show_more').click(function () {
$('.' + this.id).slideDown();
});
But when I have for example 100 divs, it's not practical to identify each <a>
with an id and put in .hidden class this id.
答案 0 :(得分:3)
您可以遍历DOM(从单击的元素开始)以找到正确的隐藏元素。
$('.show_more').click(function(){
$(this).closest('.news').find('.hidden').slideDown();
});
答案 1 :(得分:0)
我认为您可以使用parent()
和children()
来执行此操作。
以下是一个例子:
$('.show_more').click(function(){
$(this).parent().children('.hidden').slideDown();
});
答案 2 :(得分:0)
查看你的html你显示/隐藏的元素是下一个元素,所以.next()
可能是你最好的选择 -
$('.show_more').click(function(){
if ($(this).next("div.hidden:visible").length == 0)
$(this).next("div.hidden").slideDown();
else
$(this).next("div.hidden").slideUp ();
});