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

  • 相关阅读:
    1128项目跟进
    冲刺一 (day 3)
    1118 冲刺1-需求文档(初稿)
    1117 新冲刺 day1
    0622 总结与回顾
    0621 第三次冲刺
    0617 主存空间的分配和回收
    学习进度条
    软件工程学期总结
    学术诚信与职业道德
  • 原文地址:https://www.cnblogs.com/lymvv/p/8486982.html
Copyright © 2020-2023  润新知