2012-05-14 63 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