为什么使用 $(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/