扩展jquery 1.2以包含index()

时间:2012-05-14 10:16:17

标签: jquery indexing extend

我正在与一些第三方团队合作,我无法升级到jquery 1.4+并且无法升级到1.2。我想知道是否有办法扩展库以包含index()方法。我尝试写一个快速的功能,但没有运气。

function getIndex( $elm ) {
    var $this = $elm;
    var $parent = $elm.parent();
    var $index = 0;
    $parent.children().each(function(){
        if( $this.length == $(this).length && $this.length == $this.filter($(this)).length ) {
            return $index;
        }else{
            $index++;   
        }
    });
    return $index;
}

非常感谢。

问候

菲尔

1 个答案:

答案 0 :(得分:1)

啊,找到了方法并将其添加到了!

$.fn.index = function(elem){
    // No argument, return index in parent
    if ( !elem ) {
        return ( this[0] && this[0].parentNode ) ? this.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 );
}