深入学习jquery源码之add()和andSelf()
add(expr|ele|html|obj[,con])
概述
把与表达式匹配的元素添加到jQuery对象中。这个函数可以用于连接分别与两个表达式匹配的元素结果集。
jQuery 1.4 中, .add()方法返回的结果将始终以元素在HTML文档中出现的顺序来排序,而不再是简单的添加。
参数
expr String
一个用于匹配元素的选择器字符串。
elements DOMElement
DOM元素。
html String
HTML片段添加到匹配的元素。
jQuery object
一个jqeruy对象增加到匹配的元素
expr,context Element, jQuery
expr:用于匹配元素并添加的表达式字符串,或者用于动态生成的HTML代码,如果是一个字符串数组则返回多个元素
context:作为待查找的 DOM 元素集、文档或 jQuery 对象。
添加一个新元素到一组匹配的元素中,并且这个新元素能匹配给定的表达式。
Hello
Hello Again
$("p").add("span")
[ Hello
, Hello Again ]
动态生成一个元素并添加至匹配的元素中
Hello
$("p").add("Again")
[ Hello
, Hello Again ]
为匹配的元素添加一个或者多个元素
Hello
Hello Again
$("p").add(document.getElementById("a"))
[ Hello
, Hello Again
, Hello Again ]
andSelf()
概述
加入先前所选的加入当前元素中
对于筛选或查找后的元素,要加入先前所选元素时将会很有用。
选取所有div以及内部的p,并加上border类
First Paragraph
Second Paragraph
$("div").find("p").andSelf().addClass("border");
First Paragraph
Second Paragraph
jquery源码
jQuery = function (selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init(selector, context);
}
init = jQuery.fn.init = function (selector, context) {
}
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function () {
return slice.call(this);
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function (elems) {
// Build a new jQuery matched element set
var ret = jQuery.merge(this.constructor(), elems);
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
}
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};
jQuery.fn.andSelf = jQuery.fn.addBack;
jQuery.fn.extend({
add: function (selector, context) {
return this.pushStack(
jQuery.unique(
jQuery.merge(this.get(), jQuery(selector, context))
)
);
},
addBack: function (selector) {
return this.add(selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});