为什么我们在传递给.not() 和.map() 的函数中以不同的样式使用"this"?

Why we use "this" in different styles inside the function passed to .not () and .map()?

令人困惑的是,为什么我们在传递给 .not() 的函数中使用 $(this) 并在传递给 .map () 的函数中使用 this 来引用 DOM 元素对象。

$('a').not (function () {return !$(this).attr ('class') == 'keep';})

$('a').map (function() {return this.class == 'keep'?  this.className : null;})

你测试过你的代码了吗?两个回调都传递了纯 DOM 节点,因此如果您想使用 jQuery 函数,例如 attr.

,则需要在两者中都使用 $()

this是一个DOM节点时,您可以使用:

  1. 类似于 this.id 直接在 DOM 元素上引用 属性 使用普通 Javascript(无 jQuery 语法)。

  1. 类似于 $(this).css("display") 创建一个包含 DOM 元素的 jQuery 对象,这样您就可以对其使用 jQuery 方法。 $(this) 创建一个包含 on 元素的 jQuery 对象。

您可以使用其中任何一种,哪种更合适取决于您是否只需要简单的 Javascript 属性 访问权限,或者您是否需要一个 jQuery 然后可以调用的对象 jQuery方法就可以了。根据情况使用哪种情况。


仅供参考,在您的示例中,您可能应该使用 this.className,而不是 this.class。来自 MDN 的注释:

The name className is used for this property instead of class because of conflicts with the "class" keyword in many languages which are used to manipulate the DOM.