Why doesn't my jQuery selector notice when I remove a class?
I have an element contained in a parent element with the class active
, like so:
<div class="active">
<div class="button"></div>
</div>
I have jQuery set up to handle a click on my button
div, but only if that div is contained by an active
parent, like so:
$('.active .button').click(function(){
alert('Button clicked!');
});
I use jQuery to remove the active
class from the parent, and even after removing the class, the alert still pops up when I click on the button. This seems very unusual, since the button no longer meets the selector's criteria. It happens in Chrome, Firefox, and IE, so it seems to be the intentional behavior. Am I missing something? or is there at least an easy way to workaround this?
Here's a simple JSFiddle example for testing purposes: http://jsfiddle.net/KjuDy/开发者_开发百科. Click on a box in the top row. This pops up an alert and removes the active
class, as expected. The problem happens when you click a box in the top row even after the active
class is gone. I would expect the alert to not pop up, but it still does.
The handlers are assigned one time based on the results found in the selector when it runs (I'm guessing on DOM ready).
Modifying the class of those elements afterward doesn't affect the handlers that were bound.
If you want it to be more dynamic, place a .delegate()
handler instead on an ancestor of the elements,
$('#someContainer').delegate('.active .button','click',function(){
alert('Button clicked!');
});
If the only container that encompasses all the elements is the <body>
, then use that:
$('body').delegate('.active .button','click',function(){
alert('Button clicked!');
});
Your example, updated: http://jsfiddle.net/KjuDy/1/
jQuery is binding to DOM elements that match when you first bind the click event.
Look at jQuery live.
精彩评论