【问题标题】:jQuery: How does functions works just by dots (.) [duplicate]jQuery:函数如何仅通过点(。)[重复]
【发布时间】:2023-03-20 17:12:01
【问题描述】:

自从我学习了 jQuery,我一直想知道 jQuery 是如何通过添加点 . 来一个接一个地执行一个函数的(不知道它的真名,抱歉);

$("#somediv").fadeIn("fast").css("background","blue");

当淡入淡出效果完成后,CSS 函数就会执行。就像你可以一个接一个地执行你想要的任何功能。

我该怎么做?

注意:如果我命名有错误,请纠正我,我只是想学习。

【问题讨论】:

  • 每个 jQuery 函数都返回一个 jQuery 对象,然后你可以在最后一个函数之后立即调用它的方法。
  • @ArunPJohny - 刚刚注意到这是我去年问的一个问题......

标签: javascript jquery


【解决方案1】:

它被称为method chaining,其中一个方法返回它调用它的对象。

您也可以参考以下关于该主题的帖子
How can jQuery do method chaining
how does jquery chaining work?

【讨论】:

    【解决方案2】:

    它返回相同类型的对象,这是一个非常简单的示例来演示该技术:

    var Counter = function(){
        this.val = 0;    
    };
    
    Counter.prototype.increment = function(){
        ++this.val;
        return this;
    };
    
    Counter.prototype.decrement = function(){
        --this.val;
        return this;
    };
    
    Counter.prototype.log = function(){
        console.log(this.val);
        return this;
    };
    
    var o = new Counter();
    o.increment().increment().decrement().log().increment().log();
    

    【讨论】:

      【解决方案3】:

      简短的回答非常简单。每个方法都返回与传递给它的选择器匹配的元素集合,从而允许将同一个集合传递给下一个链式方法。

      在源代码中查找return this

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-10
        • 2017-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-22
        相关资源
        最近更新 更多