【问题标题】:add callback function in jquery plugin execute after some action在 jquery 插件中添加回调函数在某些操作后执行
【发布时间】:2015-02-07 07:56:15
【问题描述】:

如何在jquery插件中添加回调函数,
我尝试在handle点击后插入回调函数

$.fn.dropdown = function(options) {
  // options
  var defaults = {
    multiple: false,
    afterClick: function() {},
  }; 
  if (typeof options === "undefined") {
    var options = defaults;
  }

  if ($(this).hasClass('multiple')) {
    options.multiple = true;
  }
  var settings = $.extend(defaults, options);
  // end: options

  var handle = $(this).find('.handle');
  var handle_text = $(this).find('.handle').text();
  var dropdown_list_container = $(this).find('.dropdown-list-container');

  // click
  $(handle).on('click', function() {
    var status = parseInt($(dropdown_list_container).attr('data-active'));
    if (status != 1) {
      $(dropdown_list_container).show();
      $(dropdown_list_container).attr('data-active', 1);
    } else {
      $(dropdown_list_container).hide();
      $(dropdown_list_container).attr('data-active', 0);
    }


  });
  // end: click

  // ..
};


$(el).dropdown({
  multiple: false,
  afterClick: function() {
    console.log('click');
  },
});

【问题讨论】:

    标签: jquery jquery-plugins callback


    【解决方案1】:

    只需调用 settings.afterClick 函数(可能在 DOM 元素实例的上下文中):

    $(handle).on('click', function () {
        var status = parseInt($(dropdown_list_container).attr('data-active'));
        if (status != 1) {
            $(dropdown_list_container).show();
            $(dropdown_list_container).attr('data-active', 1);
        } else {
            $(dropdown_list_container).hide();
            $(dropdown_list_container).attr('data-active', 0);
        }
    
        settings.afterClick.call(this);
    });
    

    如果插件配置中没有提供afterClick,则默认调用空函数:afterClick: function() {}

    【讨论】:

      猜你喜欢
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 2013-12-23
      相关资源
      最近更新 更多