jQuery中有个rootjQuery变量,大家一定不陌生吧,根据源代码上的定义和注解如下:
// A central reference to the root jQuery(document)
rootjQuery,
那么该变量具体有什么作用呢?为什么要有这个?带着这个疑问,我分析了jQuery源码,发现该变量的存在使jQuery.fn.find函数和jQuery.fn.ready函数可以级联使用,少传上下文参数。
大家都知道,jQuery可以让代码可以级联使用如下:
$("#main").find(".menuitem").attr("color",red);
这里的find是执行在$("#main")运行后的上下文中,jQuery为了方便级联编码,在find函数中用了this来获取当前的环境,并针对其包含的每个元素执行查找符合条件的元素过程,其代码如下:
find : function(selector) {
<span style="white-space:pre"> </span>var i, ret = [], self = this, len = self.length;
<span style="white-space:pre"> </span>if (typeof selector !== "string") {
<span style="white-space:pre"> </span>return this.pushStack(jQuery(selector).filter(
<span style="white-space:pre"> </span>function() {
<span style="white-space:pre"> </span>for (i = 0; i < len; i++) {
<span style="white-space:pre"> </span>if (jQuery.contains(self[i], this)) {
<span style="white-space:pre"> </span>return true;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}));
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>for (i = 0; i < len; i++) {
<span style="white-space:pre"> </span>jQuery.find(selector, self[i], ret);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>// Needed because $( selector, context ) becomes $( context
<span style="white-space:pre"> </span>// ).find( selector )
<span style="white-space:pre"> </span>ret = this.pushStack(len > 1 ? jQuery.unique(ret) : ret);
<span style="white-space:pre"> </span>ret.selector = this.selector ? this.selector + " "
<span style="white-space:pre"> </span>+ selector : selector;
<span style="white-space:pre"> </span>return ret;
},
若当前环境的元素个数为0(也就是$("#main")没有符合条件的元素时),那么就不会执行find函数。
另外,$("#main")函数在获取id=main的元素过程中,实际也调用了find函数,若没有一个有元素的jQuery对象作为上下文,那么可想而知该函数始终返回空集合。为此,jQuery定义了rootjQuery,同时赋予了它合理的上下文,即document,赋值代码如下:
rootjQuery = jQuery(document);
在jQuery.fn.init的定义中是如下这样调用find的:
return (context || rootjQuery).find(selector);
其中,context是代码在调用init函数时指定的上下文对象,也就是jQuery(selector, context)中的context。
对于ready函数也同样道理。
另外rootjQuery在jQuery核心类库中仅在jQuery.fn.init函数中被使用。