jquery find element's position

2019-04-12 02:15发布

<ul>
   <li>one</li>
   <li>element</li>
   <li>text</li>
   <li>val</li>
</ul>

how can i get the position in the ul of the clicked li ?

3条回答
Emotional °昔
2楼-- · 2019-04-12 02:27
$('ul li').click(function() {
    alert(   $(this).parent().find('li').index(this)  );
});

Reference

I only tested with one <ul>. You'll need to .each if you're doing this on multiple <ul>s.

查看更多
Juvenile、少年°
3楼-- · 2019-04-12 02:39

you can do it with index() http://docs.jquery.com/Core/index

查看更多
The star\"
4楼-- · 2019-04-12 02:40

I think this will do it for you:

$("li").click(function () {

   alert($(this).index());

});

Note that the index() function returns the index of the item in the jquery collection. If you have multiple lists on the page, make sure your selector only selects the list items that you want.

查看更多
登录 后发表回答