我正在玩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();

最佳答案

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

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


现在,console方法是可链接的!

关于javascript - JavaScript/jQuery:如何链接使用console.log()的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30157097/

10-12 12:59
查看更多