考虑一下您想要向页面上的许多链接添加 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()
方法时,处理函数的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 对象。仅用一个参数调用它。以下是该方法的相关部分(请注意,在我们的示例中,name
和 selector
都是 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
});
您可以看到这一点,因为您的警报
是通过单击文档中的任意位置(而不仅仅是链接)来触发的。
这个故事的寓意是什么?停止使用 .live()
!
关于javascript - 为什么 jQuery add() 方法似乎没有返回 jQuery 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11431980/