I'm playing around with jQuery plugin development, and I'd like to chain methods. I read in the jQuery tutorial (https://learn.jquery.com/plugins/basic-plugin-creation/) that you can chain methods by adding return this; to the end of the method, and that works for the first method (test 1). How can I do that for the second method (test 2), which uses console.log? Can all methods be chained?

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

1 个解决方案

#1


The second method should return the jQuery instance. The fact that the event handler uses console.log function has nothing to do with the returned value of that method. As on returns the jQuery object you can code:

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

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

Now the console method is chainable!

现在控制台方法是可链接的!

更多相关文章

  1. 在体html中搜索文本的最佳方法是什么?
  2. jQuery 事件绑定方法(bind hover toggle live.... )、删除事件方法
  3. jQuery Ajax 方法调用 Asp.Net WebService
  4. jqueryui autocomplete 插件 点击 显示选项设置方法
  5. jQuery中的bind绑定事件与文本框改变事件的临时解决方法
  6. js和jquery使按钮失效为不可用状态的方法
  7. jquery刷新iframe页面的方法
  8. 【jQuery】调用delay()方法延时执行动画效果
  9. 重写ajax方法实现异步请求session过期时跳转登录页面

随机推荐

  1. android 屏幕方向切换 锁定方向
  2. Caused by: java.lang.IllegalStateExcep
  3. Android 基础 源码 工具
  4. Android 呼吸灯流程分析(一)
  5. android中校验email是否合法
  6. Android中设置控件透明度的方法
  7. 封装的一个android底部操作弹出窗
  8. Android文档阅读03—开发工具
  9. [置顶] Android修改源代码控制不锁屏
  10. android 系统状态栏的隐藏和显示