jquery's index() method searches for matching elements and returns the index value of the corresponding element, counting from 0.
If no parameters are passed to the .index() method, the return value is the position of the first element in the jQuery object collection relative to its sibling elements.
If the parameter is a set of DOM elements or jQuery objects, then the return value is the position of the passed element relative to the original collection.
If the parameter is a selector, the return value is the position of the original element relative to the element matched by the selector. If no matching element is found, -1 is returned.
The example code is as follows:
<ul> <li id="foo">foo</li> <li id="bar">bar</li> <li id="baz">baz</li> </ul> $('li').index(document.getElementById('bar')); //1,传递一个DOM对象,返回这个对象在原先集合中的索引位置 $('li').index($('#bar')); //1,传递一个jQuery对象 $('li').index($('li:gt(0)')); //1,传递一组jQuery对象,返回这个对象中第一个元素在原先集合中的索引位置 $('#bar').index('li'); //1,传递一个选择器,返回#bar在所有li中的做引位置 $('#bar').index(); //1,不传递参数,返回这个元素在同辈中的索引位置。
jquery to get the element index value index() example
For second or third level linkage
<div id="nav"> <a href="#">建站素材</a> <a href="#">jquery特效</a> <a href="#">懒人主机</a> <a href="#">前端路上</a> </div> $("#nav a").click(function(){ //四个经典的用法 var index1 = $("#nav a").index(this); var index2 = $("#nav a").index($(this)); var index3 = $(this).index() var index3 = $(this).index("a") alert(index3); return false; });
<html> <head> <script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ alert($(".hot").index($("#favorite"))); }); }); </script> </head> <body> 请点击下面的按钮,以获得 id="favorite" 的元素相对于 jQuery 选择器 (class="hot") 的 index: <button>获得 index</button> <ul> <li>Milk</li> <li class="hot">Tea</li> <li class="hot" id="favorite">Coffee</li> </ul> </body> </html>
The above is the detailed content of Detailed explanation of jquery getting element index() method instance. For more information, please follow other related articles on the PHP Chinese website!