起初以为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应该是比较不错的选择。
参考:http://remysharp.com/2007/04/12/jquerys-this-demystified/
再举个列子:
<a href="#" οnmοuseοver="getNodeBodyInfo(this,'node/5')">testLink</a>
javascript函数是:
1 function getNodeBodyInfo(obj,url){
2 $.get(url, function(data){
3 var tmpStr;
4 //alert(url);
5 tmpStr = data.slice(data.indexOf('<div id="node-'),data.indexOf('<div id="book-'));
6 //alert(tmpStr);
7 tmpStr = tmpStr.slice(tmpStr.indexOf('<p>'),tmpStr.indexOf('</p>'));
8 obj.title = tmpStr;//此处也可以这样写$(obj).attr(’title’, tmpStr);
9
10 $(obj).tooltip({
11
12 track: true,
13 delay: 0,
14 showURL: false,
15 opacity: 1,
16 fixPNG: true,
17 showBody: " - ",
18 extraClass: "pretty fancy",
19 top: -15,
20 left: 5
21 });
22 });
23
24 }
看看红色和蓝色代码部分,这是jquery对象与html元素之前的转化,挺有意思