jQuery中this与$(this)的区别
例子:
$(document).ready(function() {
$("#orderedlist li:last").hover(function() {
$(this).addClass("green");
},function(){
$(this).removeClass("green"); # $(this)
});
});
$(document).ready(function() {
// use this to reset several forms at once
$("#reset").click(function() {
$("form").each(function() {
this.reset(); # this
});
});
});
1.如果要使用html元素本身的属性或方法就需要使用this,如果要使用jQuery包装后的方法或属性就要$(this),($(this) 表示包装过的一个 jQuery 对象,拥有 jQuery 的一些方法,比如 $(this).addClass(), $(this).hide()...)
般则有如下的关系.
$(this)[0] == this
又如:
<a href="http://segmentfault.com/q/1010000000125418" target="_blank" data-id="1010000000125418">jQuery</a>
$('a').click(function(){
this.innerHTML==$(this).html()=='jQuery';//三者是一样的.
this.getAttribute('href')==this.href==$(this).attr('href')//三者是一样的;
this.getAttribute('target')==this.target==$(this).attr('target')//三者是一样的;
this.getAttribute('data-id')==$(this).attr('data-id')//二者是一样的;
});
例子:
$("#textbox").hover(
function() {
this.title = "Test";
},
fucntion() {
this.title = "OK”;
}
); 如果将this换成$(this)就不是那回事了,Error--报了。
这里的$(this)是一个JQuery对象,而jQuery对象沒有title 属性,因此这样写是错误的。
JQuery拥有attr()方法可以get/set DOM对象的属性,所以正确的写法应该是这样:
正确的代码:
$("#textbox").hover(
function() {
$(this).attr(’title’, ‘Test’);
},
function() {
$(this).attr(’title’, ‘OK’);
}
);

浙公网安备 33010602011771号