源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JQuery this 和 $(this) 的区别

  • 时间:2020-07-26 11:20 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JQuery this 和 $(this) 的区别
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.
[u]复制代码[/u] 代码如下:
$("#textbox").hover( function() { this.title = "Test"; }, fucntion() { this.title = "OK”; } );
这里的this其实是一个Html 元素(textbox),textbox有text属性,所以这样写是完全没有什么问题的。 但是如果将this换成$(this)就不是那回事了,Error–报了。 Error Code:
[u]复制代码[/u] 代码如下:
$("#textbox").hover( function() { $(this).title = "Test"; }, function() { $(this).title = "OK"; } );
这里的$(this)是一个JQuery对象,而jQuery对象沒有title 属性,因此这样写是错误的。 JQuery拥有attr()方法可以get/set DOM对象的属性,所以正确的写法应该是这样: 正确的代码:
[u]复制代码[/u] 代码如下:
$("#textbox").hover( function() { $(this).attr('title', ‘Test'); }, function() { $(this).attr('title', ‘OK'); } );
使用JQuery的好处是它包裝了各种浏览器版本对DOM对象的操作,因此统一使用$(this)而不再用this应该是比较不错的选择。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部