手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >JQuery this 和 $(this) 的区别
JQuery this 和 $(this) 的区别
摘要:Whatis"this"?Inmanyobject-orientedprogramminglanguages,this(orself)isa...

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应该是比较不错的选择。

【JQuery this 和 $(this) 的区别】相关文章:

体验jQuery和AngularJS的不同点及AngularJS的迷人之处

window.onload与$(document).ready()的区别分析

JQuery分屏指示器图片轮换效果实例

Javascript监视变量变化的方法

动态加载iframe

jQuery插件实现适用于移动端的地址选择器

浅谈javascript中的闭包

document 和 document.all 分别什么时候用

JQuery中attr方法和removeAttr方法用法实例

Js和JQuery获取鼠标指针坐标的实现代码分享

精品推荐
分类导航