jQuery中的rootjQuery用途

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函数中被使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值