当你用的是jquery时,就用$(this),如果是JS,就用this
1
|
$( this ).html( $( this ).html() + " BAM! " + i ); |
这个里的html()是JQUERY方法,用$(this).html(),当然,JS里也有相似方法innerHTML,如果用innerHTML,就要这样写了:
1
2
|
this .innerHTML(); this .reset(); |
这里的reset是JS方法,所以同上得用this.reset();
jquery对象$(this)[0]等同于JS里的元素this,这里的this是一样的,相信你应该看出来了,JS里的元素只要包上$()就是jquery对象了,而jquery的对象只要加上[0]或者.get(0),就是js元素了。
$(this)是jquery对象,this就是简单指当前元素。jquery对象不能直接指定元素的属性(ele.style),需要get(index)或者直接(index)取得对象中元素才行
JQuery中的 $() 这个符号,实际上这个符号在JQuery中相当于JQuery(),即$(this)=jquery(this);也就是说,这样可以返回一个jquery对象。那么,当你在网页中alert($(‘#id‘));时,会弹出一个[object Object ],这个object对象,也就是jquery对象了。
那么,我们再回过头来说$(this),这个this是什么呢?假设我们有如下的代码:
1
2
3
4
5
6
7
|
$( "#desktop a img" ).each( function (index){ alert($( this )); alert( this ); } |
那么,这时候可以看出来:
alert($(this)); 弹出的结果是[object Object ]
alert(this); 弹出来的是[object HTMLImageElement]
jQuery中this与$(this)的区别
1
2
3
4
5
6
7
8
|
$( "#textbox" ).hover( function () { this .title = "Test" ; }, fucntion() { this .title = "OK”; } ); |
这里的this其实是一个Html 元素(textbox),textbox有text属性,所以这样写是完全没有什么问题的。
但是如果将this换成$(this)就不是那回事了,Error--报了。this与$(this)的区别在此。
1
2
3
4
5
6
7
8
9
|
//Error Code: $( "#textbox" ).hover( function () { $( this ).title = "Test" ; }, function () { $( this ).title = "OK" ; } ); |
这里的$(this)是一个JQuery对象,而jQuery对象沒有title 属性,因此这样写是错误的。
JQuery拥有attr()方法可以get/set DOM对象的属性,所以正确的写法应该是这样:
正确的代码:
1
2
3
4
5
6
7
8
|
$( "#textbox" ).hover( function () { $( this ).attr(’title’, ‘Test’); }, function () { $( this ).attr(’title’, ‘OK’); } ); |
使用jQuery的好处是它包裝了各种浏览器版本对DOM对象的操作,因此统一使用$(this)而不再用this应该是比较不错的选择。
jquery里面的$(this)和this都什么时候用,有什么区别
原文:http://www.cnblogs.com/alinaxia/p/6388703.html