栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

JQuery this 和 $(this) 的区别

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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.
复制代码 代码如下:
$("#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应该是比较不错的选择。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/117853.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号