Reputation: 5413
Let's say I want to handle all links on a page, via a special function, so I do:
$('a').bind("click", handleLinks);
But I have a navbar with links that I want to handle differently. So I want to do this, which does not work:
$('#navbar a').unbind("click", handleLinks);
I do not want to specifically exclude the navbar in the first statement, because content is loaded dynamically, so the elements I need to monitor for clicks will change depending on the content. Basically I want to be able to unbind specific subsets of elements dynamically, from the larger initial subset of elements that was bound initially.
Any suggestions?
:: UPDATE ::
My sincere apologies, you're all correct - there was something funky with the order the commands were being called. Sorry!
Upvotes: 1
Views: 1385
Reputation: 7313
Strange- that looks correct. Have you tested that your initial statement is selecting what you think it does?
http://docs.jquery.com/Events/unbind
edit- Ok I did a test page
<body>
<a href="#" class="a">Test A</a>
<a href="#" class="a">Test A</a>
<a href="#" class="a">Test A</a>
<a href="#" class="b">Test B</a>
<a href="#" class="a">Test A</a>
<a href="#" class="b">Test B</a>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('a').bind("click", testClick);
$('a.b').unbind("click", testClick);
});
function testClick(){
alert("Link Clicked");
};
</script>
</body>
This works fine, however if I built my function inline I needed to unbind all events from select elements to remove it. Not sure if that applies or not but worth mentioning.
Do you mind posting a bit more code> it looks like there may be something else wrong.
Upvotes: 0
Reputation: 1275
I agree with apocalypse9 that it seems like what you have should work. Perhaps a different approach would have better results... How about using the :not selector with live(). Live will ensure the selector works with dynamically added elements.
$('a:not(#navbar a)').live("click", handleLinks);
http://docs.jquery.com/Selectors/not#selector
http://docs.jquery.com/Events/live
Upvotes: 2