首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

jQuery中this与$(this)的差异

2012-09-10 
jQuery中this与$(this)的区别$(#textbox).hover(function() {this.title Test},fucntion() {this.t

jQuery中this与$(this)的区别

  1. $("#textbox").hover(         function() {   
  2.            this.title = "Test";         },   
  3.       fucntion() {             this.title = "OK”;   
  4.       }   );
        这里的this其实是一个Html 元素(textbox),textbox有text属性,所以这样写是完全没有什么问题的。

但是如果将this换成$(this)就不是那回事了,Error--报了。this与$(this)的区别在此。

  1. Error Code:   $("#textbox").hover(   
  2.        function() {             $(this).title = "Test";   
  3.        },          function() {   
  4.           $(this).title = "OK";          }   
  5. );

这里的$(this)是一个JQuery对象,而jQuery对象沒有title 属性,因此这样写是错误的。

JQuery拥有attr()方法可以get/set DOM对象的属性,所以正确的写法应该是这样:

正确的代码:

  1. $("#textbox").hover(         function() {   
  2.          $(this).attr(’title’, ‘Test’);         },   
  3.       function() {            $(this).attr(’title’, ‘OK’);   
  4.       }   );


热点排行