这段代码是如何工作的? (jQuery 链接)

How this code works? (jQuery chaining)

我从 jQuery 插件教程中获得了这段代码。但是,我的问题是 javascript/jquery 个问题。

在代码中可以看到filter()returns一个对象,里面包含了"filtered"个对象的集合。 append() 正在操纵它。

我想问的是:append 函数如何操作所有元素而不是只对返回的对象起作用一次?

this.filter( "a" ).append(function() {
   return " (" + this.href + ")";
});

这是由于 append(function) 的性质以及初始 this 和代码中函数内部范围之间的差异。

根据 http://api.jquery.com/append/#append-function 上的 jQuery 文档,append(function) 在 "each element in the set of matched elements. [...] Within the function, this refers to the current element in the set."

上运行

因此,在您的代码中,this.filter("a") 是一个包含任何匹配元素的 jQuery 对象,而函数本身中的 this.href 在迭代过程中依次代表这些元素中的每一个集合。因此,文本将附加到所有匹配元素。