jQuery $(this)关键字 [英] jQuery $(this) keyword

查看:109
本文介绍了jQuery $(this)关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我在代码中使用了很多动画和CSS编辑功能,而且我知道可以使用$(this)简化它.

解决方案

当您像$('class-name')这样通过jQuery执行DOM查询时,它会主动在DOM中搜索该元素,并返回带有所有jQuery原型方法的该元素. /p>

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

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

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

更多信息:

网络性能与jQuery选择器

从不再存在的网络博客中引用,但出于历史原因,我将其保留在这里:

我认为,最好的jQuery性能提示之一是最大程度地减少对jQuery的使用.也就是说,要在使用jQuery和普通ol'JavaScript之间找到平衡,而"this"是一个很好的起点.许多开发人员仅将$(this)用作回调中的锤子,而忘记了这一点,但区别是明显的:

在jQuery方法的匿名回调函数中,这是一个 对当前DOM元素的引用. $(this)将此变成jQuery 对象并公开jQuery的方法. jQuery对象仅此而已 而不是增强的DOM元素数组.

Why is it important to use $(this) instead of re-selecting the class?

I am using a lot of animate and css editing in my code, and I know I can simplify it by using $(this).

解决方案

When you perform an DOM query through jQuery like $('class-name') it actively searched the DOM for that element and returns that element with all the jQuery prototype methods attached.

When you're within the jQuery chain or event you don't have to rerun the DOM query you can use the context $(this). Like so:

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

$(this) will hold the element that you originally requested. It will attach all the jQuery prototype methods again, but will not have to search the DOM again.

Some more information:

Web Performance with jQuery selectors

Quote from a web blog that doesn't exist anymore but I'll leave it in here for history sake:

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)关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆