jquery隐藏元素的实例

时间:2013-03-13 20:19:54

标签: jquery

我只想切换" .plus"和" .minus" div中的元素,在click操作上为slideToggled。

HTML

<div class="notification-box-heading">
    This is an Alert! 
    <span class="plus"><img src="http://www.cti-w.com/images/info.png"></span>
    <span class="minus"><img src="http://www.cti-w.com/images/close.png"></span>
</div>

<div class="notification-box-body"> 
    <strong>This is an alert!</strong>
    <p>This is the alert subtext.</p>
</div>

<div class="notification-box-heading">
    This is another Alert! 
    <span class="plus"><img src="http://www.cti-w.com/images/info.png"></span>
    <span class="minus"><img src="http://www.cti-w.com/images/close.png"></span>
</div>

<div class="notification-box-body"> 
    <strong>This is an alert!</strong>
    <p>This is the alert subtext.</p>
</div>

JS

$(document).ready(function () {
    //hide the all of the element with class notification-box-body
    $(".notification-box-body").hide();
    //hide the all of the element with class minus
    $(".minus").hide();
    //slides the element with class "notification-box-body" when paragraph with class "notification-box-heading" is clicked 
    $(".notification-box-heading").click(function () {
        $(this).next("div.notification-box-body").slideToggle(300);
        $(".minus").toggle();
        $(".plus").toggle();
    });
});

http://jsfiddle.net/tqD6S/2/

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

    $(".minus", this).toggle();
    $(".plus", this).toggle();

第二个参数定义范围。

答案 1 :(得分:1)

要切换的元素,.notification-box-body 包含.minus.plus元素的元素。相反,容器元素实际上是被点击的元素.notification-box-heading

尝试:

$(".notification-box-heading").click(function () {
    $(this).next("div.notification-box-body").slideToggle(300);
    $(this).find(".minus,.plus").toggle();
});

参见 jsFiddle demo

答案 2 :(得分:0)

$(document).ready(function () {
    //hide the all of the element with class notification-box-body
    $(".notification-box-body").hide();
    //hide the all of the element with class minus
    $(".minus").hide();
    //slides the element with class "notification-box-body" when paragraph with class "notification-box-heading" is clicked 
    $(".notification-box-heading").click(function () {
        $(this).next("div.notification-box-body").slideToggle(300);
        $(this).find(".minus").toggle();
        $(this).find(".plus").toggle();
    });
});

jsFiddle