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

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

 

posted @   RicoRui  阅读(71010)  评论(3编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
历史上的今天:
2008-08-20 Linq Coding -- Part Eight (Equals Topic)
2007-08-20 VS 2005 Web Application Project 项目中Profile的使用方法[程序文档]
2007-08-20 WCF读书笔记
点击右上角即可分享
微信分享提示