开发者

jQuery - click and addclass triggering another (related) click?

开发者 https://www.devze.com 2023-02-10 16:47 出处:网络
I\'m creating a menu. Menu is below. $(\'.category\').mouseover(function() { $(this).removeClass(\'category\').addCl开发者_Python百科ass(\'categoryhover\'); }).mouseout(function() { $(this).removeCl

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

0

精彩评论

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

关注公众号