JQuery this 和 $(this) 的区别
作者:bea
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(
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应该是比较不错的选择。
有用 | 无用
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应该是比较不错的选择。
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- jQuery一步一步实现跨浏览器的可编辑表格,支持IE、Firefox、Safari、Chrome、Opera
- javascript 遍历验证所有文本框的值
- JQuery 浮动导航栏实现代码
- jQuery ui1.7 dialog只能弹出一次问题
- JSON 客户端和服务器端的格式转换
- JS+Ajax+Jquery实现页面无刷新分页以及分组 超强的实现
- 动态表格Table类的实现
- javascript 单行文字向上跑马灯滚动显示
- javascript 函数调用规则
- JSON 入门指南 想了解json的朋友可以看下
- javascript 继承实现方法
- 监控用户是否关闭浏览器的js代码
- javascript 随机广告代码(图片广告)
- JS去除字符串的空格增强版(可以去除中间的空格)
- 可以读取EXCEL文件的js代码
- JavaScript 获取用户客户端操作系统版本
- JS 获取span标签中的值的代码 支持ie与firefox
- jquery 表单进行客户端验证demo
- JS 时间显示效果代码