The index method in jquery and the jqueryindex Method

Source: Internet
Author: User

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 );}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.