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()。

  • 相关阅读:
    Debian8搭建LEMP环境
    ProjectManager Beta 7 项目管理器发布
    我的Linux软件集
    修改/home内子目录的名字
    Nginx配置特定二级域名
    Debian8 安装wordpress博客
    LinuxMint18使用单独分区作为Home挂载点
    LinuxMint18配置Grub2默认启动操作系统
    《失恋33天》从绝境中走出来的故事
    爱的世界很拥挤,写在读《爱,就这么简单》之后
  • 原文地址:https://www.cnblogs.com/lymvv/p/8486982.html
Copyright © 2011-2022 走看看