MVC Bootstrap accordion - determine with JavaScript if open or closed

时间:2015-07-28 22:33:13

标签: javascript jquery model-view-controller

If we have a collapsible panel initially defined like this

 <div id="ContactDetails" class="panel-collapse collapse">

How can I test to see if it is open or closed via JavaScript?

Thanks

3 个答案:

答案 0 :(得分:1)

You can get the class list in that element (in your case div id = "ContactDetails").

var classList = document.getElementById('ContactDetails').className.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
   if (classList[i] === 'collapse') {
     //do something
   }
}

You can then browse through your classList[] if one of it is equal to "collapse".

Pure Javascript way:

var classList =$('#ContactDetails').attr('class').split(/\s+/);
$.each( classList, function(index, item){
    if (item === 'collapse') {
       //do something
    }
});

答案 1 :(得分:1)

With JQuery.hasClass:

$( "#ContactDetails" ).hasClass( "panel-collapse" )

答案 2 :(得分:1)

@Jocksan很接近,除了面板将始终具有“panel-collapse”类(如@gchq所示)。打开时,会添加“in”类,当它关闭时,将删除“in”类。因此,对于open,将返回true,关闭时返回false:

$( "#ContactDetails" ).hasClass( "in" )

以下是关于课程及其工作原理的更多信息:http://getbootstrap.com/javascript/#collapse-example-accordion