深入学习jquery源码之index()
index([selector|element])
概述:
搜索匹配的元素,并返回相应元素的索引值,从0开始计数。
如果不给 .index() 方法传递参数,那么返回值就是这个jQuery对象集合中第一个元素相对于其同辈元素的位置。 如果参数是一组DOM元素或者jQuery对象,那么返回值就是传递的元素相对于原先集合的位置。 如果参数是一个选择器,那么返回值就是原先元素相对于选择器匹配元素中的位置。如果找不到匹配的元素,则返回-1。 具体请参考示例。
参数:
index()
selector Selector
一个选择器,代表一个jQuery对象,将会从这个对象中查找元素。
element Element
获得 index 位置的元素。可以是 DOM 元素或 jQuery 选择器。
使用:
查找元素的索引值
- foo
- bar
- baz
$('li').index(document.getElementById('bar')); //1,传递一个DOM对象,返回这个对象在原先集合中的索引位置
$('li').index($('#bar')); //1,传递一个jQuery对象
$('li').index($('li:gt(0)')); //1,传递一组jQuery对象,返回这个对象中第一个元素在原先集合中的索引位置
$('#bar').index('li'); //1,传递一个选择器,返回#bar在所有li中的做引位置
$('#bar').index(); //1,不传递参数,返回这个元素在同辈中的索引位置。
contains(container,contained)
概述
一个DOM节点是否包含另一个DOM节点。
参数
container,contained Object,Object
container:DOM元素作为容器,可以包含其他元素
contained:DOM节点,可能被其他元素所包含
检测一个元素是否包含另一个元素
jQuery.contains(document.documentElement, document.body); // true
jQuery.contains(document.body, document.documentElement); // false
jquery源码
jQuery.fn.extend({
// Determine the position of an element within
// the matched set of elements
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 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);
}
});
JavaScript的indexOf的源码实现
indexOf = function (list, elem) {
var i = 0,
len = list.length;
for (; i < len; i++) {
if (list[i] === elem) {
return i;
}
}
return -1;
}
contains源码
/* Contains
---------------------------------------------------------------------- */
rnative = /^[^{]+\{\s*\[native \w/,
hasCompare = rnative.test(docElem.compareDocumentPosition);
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test(docElem.contains) ?
function (a, b) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!(bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains(bup) :
a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16
));
} :
function (a, b) {
if (b) {
while ((b = b.parentNode)) {
if (b === a) {
return true;
}
}
}
return false;
};