如果检查jQuery插件已经绑定到DOM节点,你怎么办?

首次初始化时,大多数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')); 

除非插件本身定义了一些改变它正在工作的元素的方法,否则它是不可能的。 例如:

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

在这里,我定义了一个完整的(更好,更少)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 Mutation),而不仅仅依赖于一些内部jQuery日志记录。

在我的例子中,我试图检测的插件恰好在元素$(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');

据我所知,所有jQuery Widgets都将其实例附加到他们的DOM节点。 即时通讯在我的项目中使用follwing扩展。 在一个你不知道名字的小部件上调用一个方法也很有用(例如,调用扩展小部件的基本方法)

 // 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 ; }