Jac*_*_Hu 1 javascript collections jquery this indexof
在下面的代码中:
$('body').on('click', onClickSelector, function(e) {
console.log($(this).index(onClickSelector));
console.log($(onClickSelector).index(this));
}
Run Code Online (Sandbox Code Playgroud)
两个日志似乎都给出了正确的索引值.也就是说,指数this的范围内onClickSelector收集.
但从技术上讲,这是获得该价值的正确方法吗?或者两者是否可以互换?此外,使用其中一个可能会产生任何问题吗?
但从技术上讲,这是获得该价值的正确方法吗?
它们在该实例中是可互换的(因为您还没有方便的匹配集).如果你看看封面下的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
);
},
Run Code Online (Sandbox Code Playgroud)
......他们最终是同一件事:调用内部indexOf传递集合和元素来查找.