2012-05-14 52 views
0

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

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

ANy非常感谢。

问候

菲尔

+0

https://github.com/jquery/jquery/blob/master/src/traversing.js#L137 – zerkms

+1

你可能想要做它在'noConflict推出最新版本的jQuery(什么)'模式,并慢慢移动到该版本的东西... – Matt

回答

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

只是一个不起眼的笔记 - 我也在评论中提到它:-) – zerkms