问题描述
为什么使用$(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.
更多信息:
从不再存在的网络博客中引用,但出于历史原因,我将其保留在这里:
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:
这篇关于jQuery $(this)关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!