gpt4 book ai didi

javascript - 为什么 jQuery add() 方法似乎不返回 jQuery 对象?

转载 作者:行者123 更新时间:2023-11-29 18:27:44 25 4
gpt4 key购买 nike

假设您想为页面上的许多链接添加 ajax 功能。

<a href='http://domain/purchase/car' class='purchase'>Car</a>
<a href='http://domain/purchase/bag' class='purchase'>Bag</a>
<a href='http://domain/purchase/laptop' class='purchase'>Laptop</a>

<a href='http://domain/sell/car' class='sell'>Car</a>
<a href='http://domain/sell/bag' class='sell'>Bag</a>
<a href='http://domain/sell/laptop' class='sell'>Laptop</a>

现在您可以在 JavaScript 代码中定义一些变量来引用这些链接组:

var purchaseLinks = $('.purchase'),
sellLinks= $('.sell');

好了,故事讲够了 ;)。

问题可以看this fiddle 和 this一个。

根据 jQuery's add() documentation ,返回值是一个新的 jQuery 对象。同样,AMAIK 在附加到 jQuery 对象事件的函数处理程序中,this 引用 DOM 元素。

为什么使用add()方法,handler函数的this引用了document?我不明白。我无法根据我的知识做出合乎逻辑的感知。换句话说:

jQueryObject1.click(function(){
// Here, $(this) is the jQuery object
});

jQueryObject2.click(function(){
// Here again, $(this) is the jQuery object
});

jQueryObject1.add(jQueryObject2).click(function(){
// Here $(this) refers to the Document, why?
// I think jQueryObject1.add(jQueryObject2) should equal jQueryObject3
});

更新:

感谢您的回答。我再次向读者推荐 Live is Deprecated页面,以便每个人都可以改进。

最佳答案

您的 fiddle 中的问题是 .live() 的使用。 jQuery 文档状态:

Chaining methods is not supported. For example, $("a").find(".offsite,
.external").live( ... );
is not valid and does not work as expected.

幸运的是,.live() method is deprecated ,所以你不必再担心这样的事情了。您可以改用 on 并利用事件委托(delegate)。


更新(根据@Esailija 的评论)

这就是实际发生的事情。你在这里调用 jQuery:

var purchaseLinks = $('.purchase');

这会产生一个 jQuery 对象,它有一个 selector 属性。然后调用 .add(),后者又调用内部 pushStack 方法:

return this.pushStack(isDisconnected(set[0]) || isDisconnected(all[0]) ? all : jQuery.unique(all));

pushStack method创建新的 jQuery 对象。它只用一个参数调用。下面是方法的相关部分(注意 nameselector 在我们的例子中都是 undefined):

function (elems, name, selector) {
// ...

ret.context = this.context;

if (name === "find") {
ret.selector = this.selector + (this.selector ? " " : "") + selector;
} else if (name) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}

// Return the newly-formed element set
return ret;
}

另请注意,this.context 现在是文档(因为您的原始 jQuery 对象未指定上下文,因此假定最高可能的上下文)。

因此新形成的元素集没有selector 属性,并且以文档作为其上下文。当我们调用 .live() 时,jQuery 会像这样调用 .on():

jQuery( this.context ).on( types, this.selector, data, fn );

我们可以看到问题所在。上下文是文档,没有选择器,所以事件处理程序被绑定(bind)到文档。在我们的例子中,上面一行实际上是这样的:

jQuery( document ).on( "click", function() {
//Your event handler
});

您可以通过以下事实看到这一点:您的 alert 是通过单击文档中的任意位置而不仅仅是链接触发的。

故事的寓意?停止使用 .live()!

关于javascript - 为什么 jQuery add() 方法似乎不返回 jQuery 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11431980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com