The index method in jquery and the jqueryindex Method
Problem description:Flexible use of the index method in jquery
Method signature:Index ([selector | element])
Usage Overview:P1.index (P2) // The caller P1 can be an object or a set.
Instance used:
<ul> <li class="foo">Outer1</li> <li> <ul> <li>1</li> <li id="ok" class="foo">2</li> <li>3</li> <li class="foo">4</li> </ul> </li> <li>Outer3</li></ul>
// Several test results
$ (". Foo "). index (); // 0 $ ("li "). index ("# OK"); //-1, cannot be found because $ ("li") is found in the element matching "# OK ") [0] $ ("li "). index ($ ("# OK"); // 3 $ ("li "). index (". foo "); // 0
// You can perform self-testing and research in more cases.
JQuery source code:(Recommended :)
// Determine the position of an element within// the matched set of elementsindex: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[ 0 ], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem, this );}