jQuery - click and addclass triggering another (related) click?
I'm creating a menu. Menu is below.
$('.category').mouseover(function() { $(this).removeClass('category').addCl开发者_Python百科ass('categoryhover'); }).mouseout(function() { $(this).removeClass('categoryhover').addClass('category'); });
$('.category').click(function() { $('.catmenu').removeClass('catmenu').addClass('hide'); $('.categoryact').removeClass('categoryact').addClass('category'); $('.hide', this).removeClass('hide').addClass('catmenu'); $(this).removeClass('category').addClass('categoryact'); });
$('.categoryact').live('click', function() { $('.catmenu').removeClass('catmenu').addClass('hide'); $(this).removeClass('categoryact').addClass('category'); });
Clicking on a div with the category category will give that category a new class (categoryact) and show its submenu. Presumably clicking it again will hide it. However, when the event that gives the clicked div its new class (categoryact), the function to hide it is also triggered. The result of course is that the first click, to show the submenu, appears to do nothing. Of course we know its actually firing the other one.
Can someone tell me why its triggering the "hide" functionality, and a possible way to fix it? Or damn, a way to write this simpler. There's a lot of add/remove-Class going on. ;)
Thanks.
(copied over from comments, so an answer can be accepted)
wouldn't it be easier by using jQuery's toggle() and toggleClass() functions? ... that way, you might not need a live() binding at all, as simple click() would toggle the class and the submenu
精彩评论