2017-08-12 53 views
1

在下面的代码段:JQuery索引() - 哪个方向?

$('body').on('click', onClickSelector, function(e) { 

    console.log($(this).index(onClickSelector)); 
    console.log($(onClickSelector).index(this)); 

} 

两个日志似乎给出正确的索引值。也就是this的索引,在onClickSelector集合内。

但是从技术上讲,哪种方法可以获得该值?或者两者是可以互换的?另外,是否有任何问题可能因使用一个而发生?

回答

5

但是从技术上讲,哪种方法可以获得该值?

它们在这种情况下是可以互换的(因为你还没有一套方便的匹配)。如果你看一下在幕后jQuery代码,它看起来像这样:

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 indexOf.call(jQuery(elem), this[ 0 ]); 
    } 

    // Locate the position of the desired element 
    return indexOf.call(this, 

     // If it receives a jQuery object, the first element is used 
     elem.jquery ? elem[ 0 ] : elem 
    ); 
}, 

...他们最终会被同样的事情:在内部indexOf呼叫传递一组,并找到一个元素。