如果显示另一个元素,如何隐藏折叠元素

时间:2016-05-09 12:00:35

标签: javascript jquery html twitter-bootstrap-3

我有3个按钮,当点击时会折叠并显示一个表单。我想要的是如果一个已经折叠,那么如果再点击另一个,我希望它再次隐藏。

我的小提琴:https://jsfiddle.net/77soggnv/

这是我的js代码:

$(document).ready(function(){

    //See which panel has been clicked
    $("#citizen").click(function(){
        $(this).data('clicked', true);
    });
    $("#organisation").click(function(){
        $(this).data('clicked', true);
    });
    $("#anonymous").click(function(){
        $(this).data('clicked', true);
    });

    //Hide the other panels if one is clicked
    if($("#citizen").data('clicked')){
        $("#organisation").collapse("hide");
        $("#anonymous").collapse("hide");
    }
    if($("#organisation").data('clicked')){
        $("#citizen").collapse("hide");
        $("#anonymous").collapse("hide");
    }
    if($("#anonymous").data('clicked')){
        $("#organisation").collapse("hide");
        $("#citizen").collapse("hide");
    }    

});

2 个答案:

答案 0 :(得分:4)

只需你可以这样做:

$(".btn").click(function(){
    $('.collapse.in').collapse('hide');
});

Updated Fiddle

答案 1 :(得分:0)

由于点击元素具有共同的类名和结构,因此我们不必单独附加事件。

  {'col': {0: array([['5', '', '', '', '', '']],
  dtype='|S1'), 1: array([], dtype=float64), 2: array([], dtype=float64), 3: array([], dtype=float64), 4: array([], dtype=float64), 5: array([['8', '', '', '', '', '']],
  dtype='|S1'), 6: array([], dtype=float64), 7: array([], dtype=float64), 8: array([], dtype=float64), 9: array([], dtype=float64), 10: array([], dtype=float64), 11: array([['', '8', '', '', '', '']],
  dtype='|S1'), 12: array([], dtype=float64), 13: array([], dtype=float64), 14: array([], dtype=float64), 15: array([['7', '', '', '', '', '']],
  dtype='|S1'), 16: array([], dtype=float64)}}

Fiddle

$(".btn.btn-primary").click(function() { var next = $(this).next(); $(".collapse").not(next).slideUp(); next.slideToggle(); }); 方法将返回当前元素之后的元素。