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:
- 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
- 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.
精彩评论