2

I'm using Bootstrap's button thingy

And I have a custom event attached on the buttons

$('.btn').bind('update', function(){
  // here I check if the button has the "Active" class and do something
});

$('.btn').click(function(){
  // here I trigger my event
  $(this).trigger('update');
});

So Bootstrap's click event should add the active class, but it appears it does so after my event, so my active class does not appear to be set within my event :|

Can I somehow run my click event after bootstrap's click event?


test:

http://jsfiddle.net/V55ZH/

As you can see the alert fires before the "Active" class is being set, so before Bootstrap's click event runs (the class state is unreliable to me from my event)

4

1 に答える 1

-1

From a quick glance at bootstrap's JS code (https://github.com/twitter/bootstrap/blob/master/js/bootstrap-button.js) - You can notice that the event is actually attached not directly on the button element, rather on it's container. What actually happens in your example is that bootstrap wraps the buttons with a container DIV of class "btn-group" with an attribute data-toggle="buttons-checkbox". Once clicked the event handler is fired and you can get the clicked button using the event object.

HTML

<div class="btn-group" data-toggle="buttons-checkbox">
  <button class="btn active">A</button>
  <button class="btn active">B</button>
  <button class="btn active">C</button>
  <button class="btn">D</button>
</div>

JS

$(document).ready(function(){
  $('body').on('click', '[data-toggle^=button]', function(e) {
      var btn = $(e.target);
      if (btn.hasClass('btn')) {
          alert(btn.hasClass('active'));
      }
  });
});
于 2012-08-09T18:52:26.120 に答える