javascript - Getting the index of a parent element of an event target -
with code provided:
$("#mylist").on("click", "span", function (event) { alert($(this).index()); });
and html:
<ul id="mylist"> <li>item 0 <span>span 0</span></li> <li>item 1 <span>span 1</span></li> <li>item 2 <span>span 2</span></li> <li>item 3 <span>span 3</span></li> </ul>
if click on of <span>
elements, "0" alerted. think because there 1 <span>
within each <li>
, given index of 0.
what want do, return index of <span>
's parent - in case, index of parent <li>
within <ul id="mylist">
. example, clicking on <span>span 2</span>
alert "2".
either use $(this).parent().index()
or $(this).closest('li').index()
.
the latter alert index of li if decide put new element spans , bind event that.
Comments
Post a Comment