JQuery -- this 和 $(this) 的区别
2009-08-28 09:37
531 查看
其实这个还是很好认的啦。呵呵
this,如果是取得元素的话,则对应当前元素的对象
$(this)则是当前元素被jQuery处理的对象。
看看作者是怎么写的,来源:http://www.cnblogs.com/RuiLei/archive/2009/08/20/1550804.html。
起初以为this和$(this)就是一模子刻出来。但是我在阅读时,和coding时发现,总不是一回事。
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应该是比较不错的选择。
参考:http://remysharp.com/2007/04/12/jquerys-this-demystified/
--EOF--
一般来说,在代码中,尽量使用$(this),一来代码更规范一点,二来,jQuery的函数你也就可以直接调用了。如$(this).children()之类的。。
this,如果是取得元素的话,则对应当前元素的对象
$(this)则是当前元素被jQuery处理的对象。
看看作者是怎么写的,来源:http://www.cnblogs.com/RuiLei/archive/2009/08/20/1550804.html。
起初以为this和$(this)就是一模子刻出来。但是我在阅读时,和coding时发现,总不是一回事。
What is "this"?
In many object-orientedprogramming 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应该是比较不错的选择。
参考:http://remysharp.com/2007/04/12/jquerys-this-demystified/
--EOF--
一般来说,在代码中,尽量使用$(this),一来代码更规范一点,二来,jQuery的函数你也就可以直接调用了。如$(this).children()之类的。。
相关文章推荐
- jQuery中this与$(this)的区别
- jQuery中 $(this)与this的区别
- jquery中this 和 $this 的区别
- jQuery中this与$(this)的区别
- JQuery -- this 和 $(this) 的区别
- jQuery中this与$(this)的区别
- jQuery里$(this)和this的区别在哪?
- 实例讲解JQuery中this和$(this)区别
- 文章标题jquery的this与$(this)的区别与联系
- HTML中this与JQuery中$(this)的区别
- jquery中this和$(this)区别,我是这样理解的
- JQuery this和$(this)的区别及获取$(this)子元素对象的方法
- JQuery -- this 和 $(this) 的区别
- JQuery -- this 和 $(this) 的区别
- jQuery里$(this)和this的区别在哪?
- JQuery -- this 和 $(this) 的区别
- 转: JQuery this和$(this)的区别及获取$(this)子元素对象的方法
- jQuery中this与$(this)的区别
- JQuery中$(this)和this区别
- JQuery -- this 和 $(this) 的区别