zoukankan      html  css  js  c++  java
  • jquery里$(this)和this的区别在哪

    下面两段代码在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()。

  • 相关阅读:
    面试题 41 和为s的两个数字VS 和为S的连续整数序列
    面试题 40 数组中只出现一次的数字
    面试题 39 二叉树的深度
    面试题 38数字在排序数组中出现的次数
    面试题 37 两个链表的第一个公共节点
    面试题36 数组中的逆序对
    面试题 35 第一个出现的字符
    省选模拟65 题解
    省选模拟64 题解
    省选模拟63 题解
  • 原文地址:https://www.cnblogs.com/lymvv/p/8486982.html
Copyright © 2011-2022 走看看