I get 2 alert when I click on the sub menu, the pop up first says 1 and then a second pop up gives me 2. I would like the alert to be 0,1,2,3 etc in correct sequence as per navigating an array. Is it not the sub menu item just the following item in an array?
<ul id="menu">
<li><a href="page1">Item 1</a></li>
<li><a href="page2">Item 2</a>
<ul id="sub-menu">
<li><a href="page3">Item 3</a></li>
</ul>
</li>
<li><a href="page4">Item 4</a></li>
</ul>
Jquery:
jQuery (function($) {
$("#menu .menu li").each(function (index) {
var item = $(this);
$("a", item).click(function (e) {
e.preventDefault();
alert(index);
});
});
});
A way without using
event.stopPropagation():It will only trigger for the immediate child of
li.Here is the working example.