bootstrap-collapse.js hide and show events

2019-02-25 00:05发布

问题:

I'm having a problem with boostrap-collapse.js show.bs.collapse and hide.bs.collapse events - those events do not fire up when invoked for the first time (e.g. page loads -> on.show = event is not fired -> on.hide = event is not fired -> on.show = event is fired) . After showing / un-hiding the element those events get fired up as intended.

HTML

<div class = "student" id = "stud1" onclick = "return expandTable(this,'stud1exp')">  
// header and stuff
</div>

<div class="panel-collapse collapse" id = "stud1exp">
// info that I want to show/hide 
</div>

JS

function expandTable(self,invoke){
    $("#"+invoke).collapse('toggle');
    if (self.style.backgroundColor == "rgb(204, 238, 204)"){
      $("#"+invoke).on('hide.bs.collapse',function(){
          // do something when disabled...
      });
    }
    else{
      console.log("I am firing up here");
      $("#"+invoke).on('show.bs.collapse',function(){
        // do something when enabled
      });
    }
}

I have tried to set the default state of expandable elements with

$("#"+divs[i].id).collapse({toggle:false});

but that didn't result in anything. Is there anything that I am missing? Cheers!

回答1:

Fixed by creating event handler first and then invoking a .collapse('toggle') event:

  $("#"+invoke).on('show.bs.collapse',function(){
    // do something when enabled
  });
  $("#"+invoke).collapse('toggle');