I have something like this
<div id="dropdown-menu">
<div class="visiblestuff"></div>
<div class="foldoutstuff">
<form>
<some input value/>
</form>
</div>
</div>
I want the #dropdown-menu to be clickable but not it's children so I did this:
$(function() {
var DropdownChildren = $('div#dropdown').children();
$('div#dropdown').not(DropdownChildren).click(function(event) {
var $this = $(this);
$this.toggleClass('active');
$('.foldoutstuff').toggle();
});
});
This works for the background but not the form nodes... I think the problem is caused by the toggle(开发者_JAVA百科) on foldoutstuff
please advise
Have you tried to stop the event propagation from the children?
$(function() {
$('div#dropdown').children().click(function(event) {
event.stopPropagation();
});
$('div#dropdown').click(function(event) {
var $this = $(this);
$this.toggleClass('active');
$('.foldoutstuff').toggle();
});
});
An alternate approach to @Svetlin's answer (which requires less handlers to be bound), is as follows:
$(document).ready(function () {
$('#dropdown').bind('click', function (e) {
if (e.target == this) { // Check it was this element clicked on; not a child
var $this = $(this);
$this.toggleClass('active');
$('.foldoutstuff').toggle();
}
});
});
See the target
attribute of the Event object
精彩评论