Reputation: 2597
When i clicking on menu item i get 2 click events instead of one - where is the problem?
HTML:
<nav class="nav-collapse">
<ul class="nav">
<li class="dropdown active">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Menu 1 <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a data-toggle="tab" href="#1">Item</a></li>
<li><a data-toggle="tab" href="#2">Item</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Menu 2 <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a data-toggle="tab" href="#3">Item</a></li>
<li><a data-toggle="tab" href="#4">Item</a></li>
</ul>
</li>
</ul>
</nav>
JS
jQuery('nav li').on('click', 'a[data-toggle="tab"]', function(){
console.log(this);
});
http://jsfiddle.net/nonamez/ekMSy/1/
Upvotes: 4
Views: 1832
Reputation: 53198
Because the event is being propagated to the parent li
.
You need to prevent that action using stopPropagation
:
jQuery('nav li').on('click', 'a[data-toggle="tab"]', function(e){
e.stopPropagation();
alert(this);
});
Here's an updated Fiddle.
Upvotes: 1
Reputation: 50905
I think people are thinking too hard about this. Just remove the li
part of the selector:
jQuery('nav').on('click', 'a[data-toggle="tab"]', function(e){
e.preventDefault();
alert(this);
});
The reason you had the problem before is because the target elements (a[data-toggle="tab"]
) are found twice from this parent selector: 'nav li'
(since you have nested menus).
Of course, another option is to change the main selector to jQuery('nav > li')
so it only selects the immediate children <li>
elements, but I really don't see a use for that. Your main point is just to target all the a[data-toggle="tab"]
, so just keep the container as nav
. Sure, it makes for a bigger parent for the event delegation, but technically it'll only bind one event (instead of one to each <li>
) and it allows for a[data-toggle="tab"]
to be anywhere in the ul.nav
element.
Upvotes: 2
Reputation: 50563
Because you have li inside li, try this instead:
jQuery("nav li:has('a[data-toggle]')").on('click', 'a[data-toggle="tab"]', function(){
console.log(this);
});
Another solution, more cleaner in my opinion is to use the parent <ul>
as the element to attach your event delegation handler, like this:
jQuery("ul.nav").on('click', 'a[data-toggle="tab"]', function(){
console.log(this);
});
Upvotes: 0