【问题标题】:JQuery index() - Which way around?JQuery index() - 哪种方式?
【发布时间】:2018-01-20 23:27:17
【问题描述】:
在以下代码中:
$('body').on('click', onClickSelector, function(e) {
console.log($(this).index(onClickSelector));
console.log($(onClickSelector).index(this));
}
两个日志似乎都给出了正确的索引值。即this 的索引,在onClickSelector 集合中。
但从技术上讲,哪种方法是获得该价值的正确方法?还是两者可以互换?另外,使用其中一个会不会出现任何问题?
【问题讨论】:
标签:
javascript
jquery
collections
this
indexof
【解决方案1】:
但从技术上讲,获取该值的正确方法是什么?
在这种情况下它们是可以互换的(因为您还没有手边的匹配集)。如果你看看幕后的 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 的调用传入一个集合和一个要查找的元素。