当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JQuery this 和 $(this) 的区别

Javascript
Add a Table to a Word Document
Add Formatted Text to a Word Document
用jscript实现新建word文档
用jscript实现新建和保存一个word文档
Open and Print a Word Document
Use Word to Search for Files
Convert Seconds To Hours
Sample script that deletes a SQL Server database
Sample script that displays all of the users in a given SQL Server DB
firefox中用javascript实现鼠标位置的定位
div+css实现鼠标放上去,背景跟图片都会变化。
Locate a File Using a File Open Dialog Box
Save a File Using a File Save Dialog Box
用jscript实现列出安装的软件列表
List the Stored Procedures in a SQL Server database
Display SQL Server Login Mode
Display SQL Server Version Information
List all the Databases on a SQL Server
用jscript启动sqlserver
Stop SQL Server

Javascript 中的 JQuery this 和 $(this) 的区别


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 369 ::
收藏到网摘: n/a

起初以为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应该是比较不错的选择。