I have ul
with two inner li
. I want to get the position of of the first li
but it counts all of the li
$("#clicked_job li").click(function() { var index = $(this).index(); alert(index); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="clicked_job"> <li> <ul> <li></li> <li></li> <ul> </li> <li> <ul> <li></li> <li></li> <ul> </li> </ul>
Use e.stopPropagation();
to stop triggering the event of parent li
. With this your code works fine and give the proper index of inner li
with only one alert.
$("#clicked_job li").click(function(e) { e.stopPropagation(); var index = $(this).index(); alert(index); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="clicked_job"> <li> <ul> <li>1</li> <li>2</li> </ul> </li> <li> <ul> <li>1</li> <li>2</li> </ul> </li> </ul>
The event.stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.
Firstly your HTML is invalid. You're missing several closing tags, and instead have opened new tags.
Secondly, as you have nested the li
tags you need to call stopPropagation()
on the event that's raised in order to stop the event bubbling up the DOM. Try this:
$("#clicked_job li").click(function(e) { e.stopPropagation(); var index = $(this).index(); console.log(index); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="clicked_job"> <li> <ul> <li></li> <li></li> </ul> </li> <li> <ul> <li></li> <li></li> </ul> </li> </ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.