爱程序网

jquery中的index方法

来源: 阅读:

问题描述:灵活使用jquery中的index方法

方法签名:index([selector|element])

用法概述:P1.index(P2)  //调用者P1可以为对象或集合

  1. 参数为空,返回P1[0]在父容器内的索引;
  2. 参数为字符串(即传入了一个选择器selector),返回P1[0]在P2的所有匹配中的索引,即只要传入字符串,就是在P2匹配的元素中查找P1[0];
  3. 参数为js对象或jquery对象(即传入了一个或一组element),则返回P2[0]在P1中的索引,即只要传入的是对象,就是在P1中查找P2[0];和传入字符串的情况正好相反;

使用实例: 

<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>

 

//几个测试结果 
$(".foo").index(); //0 $("li").index("#ok"); //-1,找不到,因为是在匹配"#ok"的元素中查找$("li")[0] $("li").index($("#ok")); //3 $("li").index(".foo"); //0
//更多情况可自行测试和研究

jQuery源码: (推荐:)

// Determine the position of an element within
// the matched set of elements
index: 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 );
}

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助