开发者

jQuery click event still firing on filtered element

I'm trying to filter button events based on whether they have a CSS class assigned to them or not.

Assume I have a button like this:

<button id="save-button" class="ui-state-default ui-corner-all">Save</button>

I want to get jQuery to select all buttons that currently do not have a class of "ui-state-d开发者_如何学运维isabled". The selector I'm using looks like this:

$('#save-button:not(.ui-state-disabled)').click(function() {
   ...
});

When the button is clicked, I'll call a different function, do some stuff and then add the class 'ui-state-disabled' to the button. However the button still continues to accept click events.

I'm guessing this is because of two possible causes:

  1. The event binder looks only at the initial state when binding the click event and doesn't recognise that a new class has been added later on
  2. My filter ['... :not(.ui-state-disabled)] is not correct

Any observations?


You can use .live() to do what you want, like this:

$('#save-button:not(.ui-state-disabled)').live('click', function() {
   ...
});

Or, check for the class when the click handler fires, like this:

$('#save-button').click(function() {
  if($(this).hasClass('ui-state-disabled')) return;
  ...
});

Your #1 is correct for the reason, the selector finds the elements that match at that time and binds a click handler to them...doesn't matter what classes or IDs they have later, the handler is bound to the element. .live() listens for bubbles and checks that the selector matches when the event happens, so it works...or you check yourself inside the click handler like I have in the second option above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜