28

大多数 jQuery 插件在您第一次初始化它们时都绑定/绑定到 DOM 节点。

$('#foo').bar({options: ...});

如何查看当前绑定到 DOM 节点的插件或对象#foo

if($('#foo').bar)
if($.inArray('bar', $('#foo').eq(0)))
if($('#foo').eq(0).indexOf('bar'))
if($('#foo').hasOwnProperty('bar'))

例如,可以将事件绑定到这样的对象

console.log($('#foo').data('events'));
4

3 回答 3

9

除非插件本身定义了某种方式来改变它正在处理的元素,否则这是不可能的。例如:

$.fn.extend({
  foo: function() { console.log("I am foo!"); }
});

$('#bar').foo();

在这里,我定义了一个完整的(嗯,more-o-less)jQuery 插件,它甚至不尝试与其调用元素进行交互。不过,您可以在任何 jQuery 包装的元素集合上随意使用它,因为任何 jQuery 包装的元素集合在其原型中都有jquery.js此方法,因为这行(来自):

jQuery.fn = jQuery.prototype = { ... }

...在$.fn.extend被调用插入该插件之后,没有双关语。

但即使我的插件需要以某种方式更改其调用元素,如下所示:

$.fn.extend({
  bar: function() { this.html('I am all bar now!'); }
});
$('#bar').bar();

...我仍然需要,基本上,用一些外部事件(DOM 突变事件)来处理这个,而不仅仅是依赖于一些内部 jQuery 日志记录。

于 2012-10-30T17:08:00.050 回答
4

就我而言,我试图检测的插件恰好将一些数据添加到元素$(element).data()存储中。我还看到插件添加类或 ID 并带有它们的名称 - 或在其中更改它们的名称。

以下是我目前正在使用的解决此问题的代码。可能不适用于大多数插件。

$.fn.extend({
    isPluginBound: function(pluginName)
    {
        if(jQuery().pluginName)
        {
            var name = pluginName.toLowerCase();

            return this.data(pluginName) || this.data(name)
                || this.attr('class').toLowerCase().indexOf(name) !== -1 // vs hasClass()
                || this.attr('id').toLowerCase().indexOf(name) !== -1;
        }
    }
});

要使用它,只需调用$('#foo').isPluginBound('bar');

于 2012-10-30T17:42:28.407 回答
1

据我所知,所有 jQuery 小部件都将它们的实例附加到它们的 DOM 节点。我在我的项目中使用以下扩展。在您不知道名称的小部件上调用方法也很有用(例如,调用扩展小部件的基本方法)

// returns first found widget instance of the first element or calls method on first widget instance of all elements
$.fn.widget = function ( method , option, value ) { 
  var wi;
  // iterate all elements 
  this.each( function() {
    var wii;
    // iterate all attached data elements, look for widget instances
    $.each( $(this).data(), function( key, data ){ 
      if ( "widgetName" in data ){ wii = data; return false } 
    })
    // if there is a widget instance but no method specified
    if ( wii && !method ) {
      wi = wii;
      return false
    }
    // if there is a widget and there is an object found with the method as the key
    else if ( wii && ( method in wii ) ) {
      // if it is truly a method of that instance, call that instance
      if ( $.isFunction( wii[method] ) ) {
        wi = wii[method].call( wii, option, value )
      } 
      // else, it is maybe a value stored in the instance you seek?
      else {
        wi = wii[method]
      }
    }
  })
  return ( wi === undefined ) ? this : wi ;
}
于 2012-10-30T17:57:51.830 回答