【问题标题】:jQuery custom eventjQuery 自定义事件
【发布时间】:2009-10-14 13:45:22
【问题描述】:

为什么没有触发?

$('#nav').bind('app:event', function (event, status) {
  console.log([event, status]);
});

当这是:

$(document).bind('app:event', function (event, status) {
  console.log([event, status]);
});

事件正在使用:

$(this).trigger('app:event', [options]);

从插件中。

这是整个区块:

/* App.js */
$(function ($) {

  // UI Panels
  $('#panels').panels({
    controls: '#nav a'
  });

  $('#nav').bind('app:event', function (event, status) {
    console.log([event, status]);
  });

});

/**
 * Plugin dir
 */
(function($) {
  // Interface
  $.fn.panels = function (options) {
    var settings = {}, current;

    if (options) {
      $.extend(settings, options);
    }

    // Setup
    $('.panel', this).hide();
    $('.panel:first', this).slideDown('slow');

    return this.each(function () {
      var self = $(this);

      $(settings.controls).click(function () {
        // Get reference
        current = this.href.substring(this.href.indexOf('#') + 1);

        // Hide all
        $('.panel', self).hide();
        // Show current
        $('#'+ current)
          .publish({            
            'panelReady': current
          })
          .slideDown();

        return false;
      });
    });
  };

  // Publish event
  $.fn.publish = function (options) {    
    var settings = {
      origin: this      
    };

    if (options) {
      $.extend(settings, options);
    }

    return this.each(function () {
      $(this).trigger('app:event', [options]);
    });
  };

}(jQuery));

我正在尝试实现类似 suplish/subscribe/observer 之类的解决方案,其中 #id 可以订阅事件

【问题讨论】:

  • $('#nav').bind() 周围有 $(document).ready() 吗?

标签: jquery custom-event


【解决方案1】:

试着把$(document).ready()放在周围。

$(document).ready(function() {
    $('#nav').bind('app:event', function (event, status) {
          console.log([event, status]);
    });
});

【讨论】:

  • 不,没有这样做,它已经在 $(function($) {});但将其移至 $(document).ready();没有改变任何东西。
【解决方案2】:

用这么少的代码很难说。您确定 $(this) 在您尝试触发时指的是 $("#nav") 吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    相关资源
    最近更新 更多