Phi*_*hil 21
我用谷歌搜索时的神奇资源, $('class-name')
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:=)
Run Code Online (Sandbox Code Playgroud)
看一下这段代码:
HTML:
<div class="multiple-elements" data-bgcol="red"></div>
<div class="multiple-elements" data-bgcol="blue"></div>
Run Code Online (Sandbox Code Playgroud)
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
}
);
Run Code Online (Sandbox Code Playgroud)
this指当前元素的DOM发动机是排序的工作,或参照。
另一个例子:
<a href="#" onclick="$(this).css('display', 'none')">Hide me!</a>
Run Code Online (Sandbox Code Playgroud)
希望你现在明白了。将this在处理时关键字对象导向系统,或者我们在这种情况下,元素的面向系统:)