一个div中的<p>的toggleClass,其中有多个具有相同类名的div </p>

时间:2014-02-11 17:16:48

标签: javascript jquery html

我试图在这些具有相同类别的div中隐藏p。我想要发生的是当你点击h3,段落显示,但只有那个div中的那些 - 不是所有带有类的div“drop”......

<div class="drop">
<h3>A heading</h3>
    <p>A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine.</p>
    <p>A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine.</p>
    <p>A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine.</p>
</div><!-- /drop -->


<div class="drop">
<h3>A heading</h3>
    <p>A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine.</p>
</div><!-- /drop -->

的jQuery

$(".drop p").addClass('hide');
$(".drop h3").click(function () {
    $(".drop p").toggleClass("show");
    $(".drop h3").toggleClass('goUp');
});
'show'和'hide'的类只是display:none和display:block in css。正如您所看到的,每个div中可能有多个p。

感谢任何帮助,谢谢

2 个答案:

答案 0 :(得分:2)

请为您的点击活动尝试此操作:

$(".drop h3").click(function () {
    $(this).nextAll().toggleClass("show");
    $(this).toggleClass('goUp');
});

<强> jsFiddle example

您希望在点击处理程序中使用this来引用已点击的元素,而不是.drop p,它将选择与该选择器匹配的所有段落。

答案 1 :(得分:1)

你也可以这样做:

$(".drop h3").click(function () {
    $(this).parent().find('p').slideToggle();
});

像这样: http://codepen.io/EightArmsHQ/pen/gjxuH

您可以同样使用您的技术:

$(".drop h3").click(function () {
    $(this).parent().find("p").toggleClass("show");
    $(this).parent().find("h3").toggleClass('goUp');
});