手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆

JQuery -- this 和 $(this) 的区别

首页 > Javascript >

其实这个还是很好认的啦。呵呵
this,如果是取得元素的话,则对应当前元素的对象
$(this)则是当前元素被jQuery处理的对象。

看看作者是怎么写的,来源:http://www.cnblogs.com/RuiLei/archive/2009/08/20/1550804.html。

起初以为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/

 --EOF--

一般来说,在代码中,尽量使用$(this),一来代码更规范一点,二来,jQuery的函数你也就可以直接调用了。如$(this).children()之类的。。




本站采用创作共享版权协议, 要求署名、非商业和保持一致. 本站欢迎任何非商业应用的转载, 但须注明出自"易栈网-膘叔", 保留原始链接, 此外还必须标注原文标题和链接.

Tags: jquery

« 上一篇 | 下一篇 »

只显示10条记录相关文章

[转载]超强大的jquery formValidator (浏览: 50912, 评论: 3)
jQuery插件---获取URL参数 (浏览: 46209, 评论: 1)
jQuery的html()等方法介绍 (浏览: 45709, 评论: 1)
取得html中的comment的内容 (浏览: 41889, 评论: 2)
jQuery的bind函数 (浏览: 40715, 评论: 1)
将Yiiframework与JQuery easyUI整合使用 (浏览: 38159, 评论: 2)
jQuery一些插件的链接[转] (浏览: 37634, 评论: 2)
取消radio的选中状态 (浏览: 36813, 评论: 1)
JQuery学习第一天 (浏览: 35447, 评论: 3)
推荐一个Jquery插件:autoComplete (浏览: 33350, 评论: 0)

3条记录访客评论

We are a group of vollunteers and startging a new scheme in our community.
Your website offered us with valuable information to work on. You have done an impressive job and our
emtire community will be grateful to you.

Post by escortsadvice.com on 2017, April 29, 5:48 AM 引用此文发表评论 #1

I am not rattling fantastic with English but
I line up this real leisurely to interpret.

Post by Rafael on 2017, April 28, 7:52 AM 引用此文发表评论 #2

Wow! After all I got a web site from where I can actually
take helpful facts concerning my study and knowledge.

Post by spashoodies.com on 2017, April 24, 11:21 PM 引用此文发表评论 #3


发表评论

评论内容 (必填):