jQuery $(this)关键字
为什么使用$(this)而不是重新选择类很重要?
我在我的代码中使用了很多动画和css编辑,我知道我可以使用$(this)来简化它。
当我用Google搜索时,神奇的资源, "what is jQuery this"
http://www.erichynds.com/jquery/jquery-and-performance-what-is-this/
在我看来,最好的jQuery性能提示之一是尽量减少你对jQuery的使用。 也就是说,在使用jQuery和普通的’JavaScript’之间找到一个平衡点,一个好的起点就是’this’。 许多开发人员将$(this)专门用作回调中的锤子而忘记了这一点,但区别在于:
当在jQuery方法的匿名回调函数中时,这是对当前DOM元素的引用。 $(this)将其转换为jQuery对象并公开jQuery的方法。 jQuery对象只不过是一个增强的DOM元素数组。
$(document).ready(function(){ $('.somediv').click(function(){ $(this).addClass('newDiv'); // this means the div which is clicked }); // so instead of using a selector again $('.somediv'); }); // you use $(this) which much better and neater:=)
看看这段代码:
HTML:
JS:
$('.multiple-elements').each( function(index, element) { $(this).css('background-color', $(this).data('bgcol')); // Get value of HTML attribute data-bgcol="" and set it as CSS color } );
this
指的是DOM引擎正在处理或引用的当前元素。
另一个例子:
Hide me!
希望你现在明白。 处理面向对象的系统时会出现this
关键字,或者就像我们在这种情况下面向元素的系统而言:)
使用$(this)可以提高性能,因为不需要在整个网页内容中多次搜索用于搜索的类/任何内容。