【问题标题】:JavaScript/jQuery: How to Chain a Method that uses console.log()JavaScript/jQuery:如何链接使用 console.log() 的方法
【发布时间】:2015-05-10 22:00:46
【问题描述】:

我正在玩 jQuery 插件开发,我想链接方法。我在 jQuery 教程 (https://learn.jquery.com/plugins/basic-plugin-creation/) 中读到,您可以通过在方法末尾添加 return this; 来链接方法,这适用于第一种方法(测试 1)。对于使用console.log 的第二种方法(测试2),我该如何做到这一点?所有方法都可以链接吗?

   // test 1
    $.fn.greenify = function () {
        this.css('color', 'green');
        return this;
    };

    // test 2
    $.fn.console = function () {
        this.on('click', function () {
            console.log('hello world');
        });
    };

    $('a').greenify().console();

【问题讨论】:

    标签: javascript jquery plugins chaining method-chaining


    【解决方案1】:

    第二种方法应该返回 jQuery 实例。事件处理程序使用console.log 函数的事实与该方法的返回值无关。 on 返回你可以编码的 jQuery 对象:

    $.fn.console = function () {
       return this.on('click', function () {
          console.log('hello world');
       });
    };
    

    现在console 方法可以链接了!

    【讨论】:

    • 谢谢!有用的答案!
    • 没有jQuery可以做到吗?
    • it 指的是什么? “如何链接使用 console.log() 的方法”?
    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    • 2017-05-23
    • 2020-11-25
    相关资源
    最近更新 更多