码迷,mamicode.com
首页 > Web开发 > 详细

jquery里$(this)和this的区别在哪

时间:2018-03-01 10:18:12      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:dom   style   ready   ever   each   ...   div   use   需要   

下面两段代码在jquery的官网见到的,何时用$(this),又何时用this呢?

$(document).ready(function() {
   $("#orderedlist li:last").hover(function() {
     $(this).addClass("green");
   },function(){
     $(this).removeClass("green"); # $(this)
   });
 });
$(document).ready(function() {
   // use this to reset several forms at once
   $("#reset").click(function() {
     $("form").each(function() {
       this.reset(); # this
     });
   });
 });

如果你要使用html元素本身的属性或者方法就需要使用this,如果你要使用jquery包装后的方法或者属性就要使用$(this),一般则有如下的关系

$(this)[0]==this;

上文的代码是要使用this的地方是要调用表单form的有reset方法,而这一方法jQuery没有包装支持,所以才有this.reset(),也可以使用$(this)[0].reset();

也就是说this是html元素对象

$(this)成为jquery对象

this 是 JavaScript 中的关键字。
$(this) 可以认为是用 jQuery 包装过 JavaScript 中的 this,包装后 $(this) 就会继承 jQuery 的方法。

本质就是JavaScript与jQuery对象的转换

$(‘a‘).click(function(){
     // 这里的 this 指向当前点击的DOM节点,也就是a。可以调用DOM方法,比如this.getAttribute, this.tagName ...
    // 这里的 $(this) 表示包装过的一个 jQuery 对象,拥有 jQuery 的一些方法,比如 $(this).addClass(), $(this).hide() ...
});

$(this)是jquery对象,能调用jquery的方法,例如click(), keyup()。
而this,则是html元素对象,能调用元素属性,例如this.id,this.value。
例如假设已经使得this和$(this)都指向了input对象了,若要获得input的值,可以this.value,但$(this)就得$(this).val()。

jquery里$(this)和this的区别在哪

标签:dom   style   ready   ever   each   ...   div   use   需要   

原文地址:https://www.cnblogs.com/lymvv/p/8486982.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!