JQuery this 和 $(this) 的区别
更新时间:2009年08月23日 19:00:13 作者:
起初以为this和$(this)就是一模子刻出来。但是我在阅读时,和coding时发现,总不是一回事。
What is "this"?
In many object-oriented programming languages, this (or self) is a keyword which can be used in instance methods to refer to the object on which the currently executing method has been invoked.
$("#textbox").hover(
function() {
this.title = "Test";
},
fucntion() {
this.title = "OK”;
}
);
这里的this其实是一个Html 元素(textbox),textbox有text属性,所以这样写是完全没有什么问题的。
但是如果将this换成$(this)就不是那回事了,Error–报了。
Error Code:
$("#textbox").hover(
function() {
$(this).title = "Test";
},
function() {
$(this).title = "OK";
}
);
这里的$(this)是一个JQuery对象,而jQuery对象沒有title 属性,因此这样写是错误的。
JQuery拥有attr()方法可以get/set DOM对象的属性,所以正确的写法应该是这样:
正确的代码:
$("#textbox").hover(
function() {
$(this).attr('title', ‘Test');
},
function() {
$(this).attr('title', ‘OK');
}
);
使用JQuery的好处是它包裝了各种浏览器版本对DOM对象的操作,因此统一使用$(this)而不再用this应该是比较不错的选择。
In many object-oriented programming languages, this (or self) is a keyword which can be used in instance methods to refer to the object on which the currently executing method has been invoked.
复制代码 代码如下:
$("#textbox").hover(
function() {
this.title = "Test";
},
fucntion() {
this.title = "OK”;
}
);
这里的this其实是一个Html 元素(textbox),textbox有text属性,所以这样写是完全没有什么问题的。
但是如果将this换成$(this)就不是那回事了,Error–报了。
Error Code:
复制代码 代码如下:
$("#textbox").hover(
function() {
$(this).title = "Test";
},
function() {
$(this).title = "OK";
}
);
这里的$(this)是一个JQuery对象,而jQuery对象沒有title 属性,因此这样写是错误的。
JQuery拥有attr()方法可以get/set DOM对象的属性,所以正确的写法应该是这样:
正确的代码:
复制代码 代码如下:
$("#textbox").hover(
function() {
$(this).attr('title', ‘Test');
},
function() {
$(this).attr('title', ‘OK');
}
);
使用JQuery的好处是它包裝了各种浏览器版本对DOM对象的操作,因此统一使用$(this)而不再用this应该是比较不错的选择。
相关文章
基于jQuery实现的Ajax 验证用户名是否存在的实现代码
基于jQuery实现的Ajax 验证用户名是否存在的实现代码,需要的朋友可以参考下。2011-04-04
jQuery使用serialize()表单序列化时出现中文乱码问题的解决办法
列化中文时出现中文乱码问题,怎么回事呢?下面给大家介绍下jQuery使用serialize()序列化表单时出现中文乱码问题的解决办法,有需要的朋友参考下2016-07-07
jQuery插件jcrop+Fileapi完美实现图片上传+裁剪+预览的代码分享
这篇文章主要介绍了jQuery插件jcrop+Fileapi完美实现图片上传+裁剪+预览的代码,非常的简单实用,效果也很棒,有需要的小伙伴可以参考下。2015-04-04
jQuery 验证插件 Web前端设计模式(asp.net)
asp.net下用户注册页面的验证代码,花了点时间将验证做成一个jQuery插件,希望对需要的朋友有所帮助。2010-10-10


最新评论