问题
This jquery toggles two things. (1) A css class and (2) displaying a div. The toggle works great if I click outside the element (Menu Toggle), but if I click inside the element itself, the div toggles, but the css class won't. Why is that?
Live preview at http://jsfiddle.net/aL7Xe/68/
I need the added css class to go away when clicking on "Menu Toggle" the second time.
<div id="menuwrap">
<a href="#" id="menutoggle">Menu Toggle</a>
<ul id="menucontainer">
<li><a href="#">One</a></li>
<li><a href="#">Two</a></li>
<li><a href="#">Three</a></li>
</ul>
</div>
this is more text
<script>
$('html').click(function() {
$('#menucontainer').hide();
$('#menutoggle').removeClass('menutoggle');
});
$('#menuwrap').click(function(event){
event.stopPropagation();
});
$('#menutoggle').click(function(event){
$('#menucontainer').toggle();
$(this).addClass('menutoggle');
});
</script>
回答1:
$('#menutoggle').click(function(event){
$('#menucontainer').toggle();
$(this).toggleClass('menutoggle');
});
http://jsfiddle.net/L5Cq3/
Fewest lines to achieve desired result.
回答2:
Change $(this).addClass('menutoggle');
to $(this).toggleClass('menutoggle');
回答3:
This is because, when you click on the Menu container, both events are fired (i.e. HTML click handler, and the div click handler).
Perhaps this is what you want:
$('#menutoggle').click(function(event){
$('#menucontainer').toggle();
if ($(this).hasClass('menutoggle')
$(this).removeClass('menutoggle');
else
$(this).addClass('menutoggle');
});
Edit
You could just use toggleClass
(credits to Juan for reminding me of the existence of that) as well. I'm pretty sure, under the hood, it does the same thing as my code above is doing.
Here's your fixed fiddle: http://jsfiddle.net/aL7Xe/69/
来源:https://stackoverflow.com/questions/11006406/jquery-toggle-css-class