jQuery $(this) 关键字

标签 jquery this

为什么使用 $(this) 而不是重新选择类很重要?

我在代码中使用了大量的动画和 CSS 编辑,并且我知道可以使用 $(this) 来简化它。

最佳答案

当您通过 jQuery 执行 DOM 查询(如 $('class-name') )时,它会主动在 DOM 中搜索该元素,并返回该元素以及附加的所有 jQuery 原型(prototype)方法。

当您处于 jQuery 链或事件中时,您不必重新运行 DOM 查询,您可以使用上下文 $(this)。就像这样:

$('.class-name').on('click', function(evt) {
    $(this).hide(); // does not run a DOM query
    $('.class-name').hide() // runs a DOM query
}); 

$(this) 将保存您最初请求的元素。它将再次附加所有 jQuery 原型(prototype)方法,但不必再次搜索 DOM。

更多信息:

Web Performance with jQuery selectors

引用一个不再存在的网络博客,但为了历史起见,我将其保留在这里:

In my opinion, one of the best jQuery performance tips is to minimize your use of jQuery. That is, find a balance between using jQuery and plain ol’ JavaScript, and a good place to start is with ‘this‘. Many developers use $(this) exclusively as their hammer inside callbacks and forget about this, but the difference is distinct:

When inside a jQuery method’s anonymous callback function, this is a reference to the current DOM element. $(this) turns this into a jQuery object and exposes jQuery’s methods. A jQuery object is nothing more than a beefed-up array of DOM elements.

关于jQuery $(this) 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12481439/

相关文章:

jQuery 错误 - 从下拉列表中选择的选项/值

javascript - 带有 xmlhttp 的通用回调函数如何在 "this"更改时发送对函数的引用

jquery - 在 jQuery 的 setInterval 中使用 $(this)

javascript - txtLatLong.split 不是 jquery 中的函数

jquery - 用于与 jsonp 通信的简单 Python HTTP 服务器

javascript - 将类的所有元素的内容放入数组中。为什么我会收到这些错误消息

javascript - 在 Jquery 中切换元素显示的可靠方法

javascript - 使用 `this` 与 Object.create(prototype)

JavaScript - 如何正确保存 "this"的状态

javascript - 这 vs $(这)