jquery插件添加事件监听器

时间:2016-07-25 14:31:47

标签: javascript jquery jquery-plugins

我有一个我创建的jquery插件,它显示内容并在类似界面的选项卡中隐藏内容。我想要的是触发一个事件,当某些内容显示我可以在我的源代码中监听,并​​根据可能的事件发起事件?

这是我的插件,

$.fn.appsTabs = function(options){

  // These are the defaults.
  var settings = $.extend({
    // These are the defaults.
    selected: "home"
  }, options );

  // Set Active
  $(this).find('.pops-tabs-navigation li[data-route="'+settings.selected+'"]').addClass('active');

  // Hide All Boxes and show first one
  $(this).find('.apps-tabs-content .pops-tab-content').addClass('cloak');
  $(this).find('.pops-tabs-content .pops-tab-content#content-'+settings.selected).removeClass('cloak');
  // Get Clicks on Li in Navigation
  $(this).find('.apps-tabs-navigation li').click(function(){
    if($(this).hasClass('active') == false) {
      // Get ID of Tab
      id = $(this).attr('id');
      tabid = 'content-'+id;

      // Set Active
      $(this).parent('.apps-tabs-navigation').find('li').removeClass('active');
      $(this).addClass('active');

      // Hide all boxes
      $(this).parent('.apps-tabs-navigation').parents('.pops-tabs').find('.pops-tabs-content .pops-tab-content').addClass('cloak');
      $(this).parent('.apps-tabs-navigation').parents('.pops-tabs').find('.pops-tabs-content #'+tabid).removeClass('cloak');
    }
  });
}

是否有可能在原型中添加一些内容并在我的主应用程序代码中监听它?

1 个答案:

答案 0 :(得分:0)

在您的插件代码中,您可以触发自定义事件并在页面javascript中收听它:

<强>插件

// Show your element (example)
$('#myElement').show();
// Trigger custom event
$(document).trigger('myCustomPluginEvent');

网页

// Event listener for custom event 'myCustomPluginEvent'
$(document).on('myCustomPluginEvent', function() {
   // Do something when custom event occurs
});