http://jsfiddle.net/KevinOrin/xycCx/1/
jQuery('.happening-main-text .readmore').click(function() {
jQuery('.divmore').toggle('slow');
return false;
});
我试图让每个链接只显示/隐藏单击的链接。我怎么能修改JS呢?我尝试了('.happening-main-text').closest('divmore')
,但也不起作用。
<div class="happening-main-text">
<p>part of text goes here part of text <a href="#" class="readmore">show/hide</a>
</p>
<div class="divmore">
<p>more test from hidden1</p>
</div>
</div>
<div class="happening-main-text">
<p>part of text goes here part of text <a href="#" class="readmore">show/hide</a>
</p>
<div class="divmore">
<p>more test from hidden</p>
</div>
</div>
<div class="happening-main-text">
<p>part of text goes here part of text <a href="#" class="readmore">show/hide</a>
</p>
<div class="divmore">
<p>more test from hidden2</p>
</div>
</div>
如果您保留HTML的当前格式,以下代码应该可以使用
jQuery('.happening-main-text .readmore').click(function() {
jQuery(this).parent().next().toggle('slow');
return false;
});
通过查看小提琴中的DOM,这可能是解决问题的一种方法:
jQuery('.happening-main-text .readmore').click(function() {
jQuery(this).parent().next().toggle('slow');
return false;
}
请查看文档中的$.next和$.eparent。此外,您可能会注意到动画是"跳跃"的,这是因为p
(相关SO问题(上的边距。删除边距可以解决这个问题。例如:
p { margin: 0; }
Kevin,试着走这条路:
$('.happening-main-text').each(function() {
$divmore = $(this).find(".divmore");
$readmore = $(this).find(".readmore");
$readmore.bind("click", {target: $divmore}, function(e) {
e.data.target.toggle();
});
});
由于html的结构,您需要向每次单击回调传递不同的目标。重构一点DOM将允许您使用$((.兄弟或其他更简单的解决方案。不管怎样,你可以在这里看看你的小提琴的工作版本:http://jsfiddle.net/xycCx/6/
解决方案如下(http://jsfiddle.net/4nJWf/):
注意:修复原始HTML 中的错误
HTML
<div class="happening-main-text">
<p>part of text goes here part of text <a href="#" class="readmore">show/hide</a>
</p>
<div class="divmore">
<p>more test from hidden1</p>
</div>
</div>
<div class="happening-main-text">
<p>part of text goes here part of text <a href="#" class="readmore">show/hide</a>
</p>
<div class="divmore")">
<p>more test from hidden</p>
</div>
</div>
<div class="happening-main-text">
<p>part of text goes here part of text <a href="#" class="readmore">show/hide</a>
</p>
<div class="divmore">
<p>more test from hidden2</p>
</div>
</div>
jQuery
jQuery('.happening-main-text .readmore').click(function() {
$(this).parents('.happening-main-text').children('.divmore').toggle('slow');
return false;
});
我知道这个问题已经得到了回答,但解决方案中似乎没有显示类divmore
中的隐藏文本,而是隐藏了happening-main-text
类的其余部分。
它应该只将.divmore
类直接切换到单击的<a>
,如下所示:
$(document).ready(function(){
$(".readmore").click(function(){
$(this).parent("p").siblings("div").toggle("slow");
});
});
这是我的小提琴