JQuery index() - 哪条路?
JQuery index() - Which way around?
在下面的一段代码中:
$('body').on('click', onClickSelector, function(e) {
console.log($(this).index(onClickSelector));
console.log($(onClickSelector).index(this));
}
两个日志似乎都给出了正确的索引值。即 this
在 onClickSelector
集合中的索引。
但从技术上讲,哪种方法是获得该值的正确方法?或者两者可以互换?另外,使用一个而不是另一个可能会出现任何问题吗?
But which is technically the correct way to get that value?
在那种情况下它们是可以互换的(因为您还没有手边的那组火柴)。如果您查看幕后的 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
传递一个集合和一个要查找的元素。
在下面的一段代码中:
$('body').on('click', onClickSelector, function(e) {
console.log($(this).index(onClickSelector));
console.log($(onClickSelector).index(this));
}
两个日志似乎都给出了正确的索引值。即 this
在 onClickSelector
集合中的索引。
但从技术上讲,哪种方法是获得该值的正确方法?或者两者可以互换?另外,使用一个而不是另一个可能会出现任何问题吗?
But which is technically the correct way to get that value?
在那种情况下它们是可以互换的(因为您还没有手边的那组火柴)。如果您查看幕后的 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
传递一个集合和一个要查找的元素。