最近是在学习JQuery,要是我早点学习了就不会一个一个的写document.getElementByID了,在学习JS的视频的时候就有一个例子,是封装了一个JS,也是实现了一个$符就能直接获取到元素,所以也是很好奇,查了一下JQuery实现的原理。
进入JQuery的源码中发现了一句话
var jQuery = window.jQuery = window.$ = function (selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context);
};
每次申明一个jQuery对象的时候,返回的是jQuery.prototype.init对象,很多人就会不明白,init明明是jQuery.fn的方法啊,实际上这里不是方法,而是init的构造函数,因为js的prototype对象可以实现继承,加上js的对象只是引用不会是拷贝,new jQuery,new jQuery.fn和new jQuery.fn.init的子对象是一样的,只是有没有执行到init的不同。
当我们使用选择器的时候$(selector,content),就会执行init(selectot,content)。
jQuery.fn = jQuery.prototype = {
init: function (selector, context) {
// 确认选择器已经提供
selector = selector || document;
// 处理DOM元素
if (selector.nodeType) {
this[0] = selector;
this.length = 1;
return this;
}
// 处理HTML字符串
if (typeof selector == "string") {
// 判断处理的是HTML字符串还是ID
var match = quickExpr.exec(selector);
// 做匹配,如果是ID
if (match && (match[1] || !context)) {
// HANDLE: $(html) -> $(array)
if (match[1])
selector = jQuery.clean([match[1]], context);
// HANDLE: $("#id")
else {
var elem = document.getElementById(match[3]);
// 确认元素已经加载
if (elem) {
// Handle the case where IE and Opera return items
// 如果是根据Name选择
if (elem.id != match[3])
return jQuery().find(selector);
// 否则直接将元素注入到JQuery对象中
return jQuery(elem);
}
selector = [];
}
// <span style="color: rgb(0, 130, 0); font-family: 'Courier New', Courier, monospace; line-height: 13.1999998092651px;">非id的形式.在context中或者是全文查找</span>
// (which is just equivalent to: $(content).find(expr)
} else
return jQuery(context).find(selector);
// HANDLE: $(function)
// Shortcut for document ready
} else if (jQuery.isFunction(selector))
return jQuery(document)[jQuery.fn.ready ? "ready" : "load"](selector);
return this.setArray(jQuery.makeArray(selector));
}
这里是init这个方法的具体代码,反正我是没怎么看懂,查了查资料发现,大概就是根据$()中输入的ID进行分类型的查询,查询完成之后返回一个JQuery对象,然后我们就可以开心的连缀了~