I'm looking to find the position (i.e. the order) of a clicked element within a list using jQuery.
I have:
<ul>
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
...
</ul>
On click of an <li>
, I want to store it's position within a variable. For example, if I clicked on Element 3, then "3" would be stored in a variable.
How could this be achieved?
Thanks much for y开发者_如何学JAVAour help!
Use index()
:
$("li").click(function() {
var index = $(this).parent().children().index(this);
alert("You clicked item " + index);
});
Indexes start at 0.
A more efficient version of Cletus' answer, which doesn't require finding parents and children:
$("li").on("click", function() {
var index = $(this).index();
alert(index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
<li>Element 4</li>
</ul>
Can also be done with plain JavaScript:
let = _this = this,
indx = Array.prototype.slice.call(_this.parentElement.childNodes).indexOf(_this);
Or, if you trying to style your ordered html list with other than CSS like <hr>
, as @Jan mentioned, use querySelectorAll('li')
instead of childNodes
.
Previous answer works fine. 2 additions:
When your list contains listitems of <a>
for example:
<ul id="test">
<li><a href="#">Element 1</a></li>
<hr /><hr />
<li><a href="#">Element 2</a></li>
<li><a href="#">Element 3</a></li>
</ul>
then you have to use var index = $(this).parent().parent().children().index(this);
Also like in above example the list contains other elements like <hr />
than you can use a filter in var index = $(this).parent().parent().children("li").index(this);
to give you index 2 for "element 3" instead of index 4.
精彩评论