jQuery init 方法中的context详解

来源:互联网 发布:诵读古兰经软件 编辑:程序博客网 时间:2024/05/17 08:43

我一直都知道jQuery的初始化方法是: $(selector, context),但是最近看了代码才发现,context并不只是限制查找那么简单:


我总结出来了几点:

<p id="n1">        <span id="n2">            <span id="n3">A</span>        </span>        <label id="n4">B</label>        <span id="n5" class="active">            <span id="n6" class="start active">C</span>                </span>        <strong id="n7" class="active">D</strong>        <span id="n8" class="active">E</span>    </p>    <p id="n9" class="active">        <span id="n10"></span>        <label id="n11"></label>        <span id="n12">            <span id="n13" class="start">F</span>        </span>    </p>

1. 当selector为String的css选择器的时候,context就是用来限制查找域的。所有需要查找的元素都会在context下面查找。

console.log($("#n2")); // n2  console.log($("#n2", $("#n3"))); // []  console.log($("span")); // 所有的span  console.log($("span", $("#n2"))); // n3


2. 当selector为html元素的时候,context可以是jQuery,Dom对象。同时也可以是prop属性对象。

当context是jQuery和Dom对象的时候,context是用来提供返回值的ownerDocument的,返回的元素的ownerDocument会根据context的ownerDocument来定。默认是document

也就是说,如果你的context是在当前document下面,那么返回元素的ownerDocument也是documetn。如果context是在某个iframe下面,那么返回元素的ownerDocument也是iframe的document.

console.log($("<span></span>")[0].ownerDocument); // 生成一个span元素,context为document  console.log($("<span></span>", $("#n2"))[0].ownerDocument); // 生成一个span元素,context为document  console.log($("<span></span>", $("iframe")[0].contentWindow.document)[0].ownerDocument); // 假设有iframe,生成一个span元素,context为iframe的document

当context是prop属性对象的时候,那么context是用来提供生成元素的属性的:

console.log($("<div></div>", {name: "123", width: 455, class: "test"})[0].outerHTML)   // Chrome下: <div name="123" class="test" style="width: 455px;"></div>


3. 当selector为jQuery或者Dom元素的时候,context是没有用的。这一点和我之前想的不同,我以为还会根据context进行一遍过滤,但是看了源码以后,并没有。

所以在这种情况下,context是完全被忽略的。

console.log($($("#n2"))); // n2  console.log($($("#n2"), $("#n3"))); // n2,并没有进行过滤  console.log($($("#n2")[0])); // n2  console.log($($("#n2")[0], $("#n3"))); // n2, 并没有进行过滤



0 0
原创粉丝点击