检测jQuery插件是否应用于多个元素?

3
我正在开发一个可以应用于多个元素的jQuery插件。该插件包含一些动画效果,我需要根据插件是否应用于多个元素来管理事件队列。
如何检测插件是应用于单个元素还是多个元素的最佳方法?
编辑...
如果插件被传递多个元素(例如$('.myClass').plugin()),则length属性可以正确地工作,但是如果在多个单独的元素上调用插件(例如$('#myElem1').plugin()和$('#myElem2').plugin()),则每次调用的长度都会返回1。
是否有一种方法可以在第二个示例中检测到多个实例?

我添加了一种方法来解决这个问题...但请记住,当它在第一个元素上调用时,计数将是1,你无法知道它将被应用于更多元素。 - Nick Craver
3个回答

5

this 在插件中,根据你的风格,指的是jQuery对象,因此你可以检查.length属性,例如:

 jQuery.fn.plugin = function(options) {
   if(this.length > 1) //being applied to multiple elements
 };

针对您的编辑:跟踪总数可能是一个更好的选择,例如:

(function($) {
  $.pluginCount = 0;
  $.fn.plugin = function(options) {
    $.pluginCount += this.length;    //add to total
    if($.pluginCount > 1) //overall being applied to multiple elements
  };
})(jQuery)

1
如果您想要一种通用的方法来测试插件是否已应用于任意一组元素,这里有一种方法:
// say we want to apply this to a bunch of elements
​​$.fn.test = function(str) {
    this.each(function() {
        // set a boolean data property for each element to which the plugin is applied
        $(this).data('test', true);
        alert(str);
    });
};


// use a simple plugin to extract the count of a specified plugin
// from a set of elements
$.fn.pluginApplied = function(pluginName) {
    var count = 0;
    this.each(function() {
        if($(this).data(pluginName)) {
            count++;
        }
    });
    return count;
};

使用这个标记:

<a href="test" class="test">Hello</a>
<br />
<a href="test" class="test">Hello</a>

这是一个测试:

$("a").test('test');

alert($("*").pluginApplied('test'));​​​​​​​​​​​​​​​​ // alerts '2'

演示:http://jsfiddle.net/B5QVC/

1
假设您通过$('some selector').myPlugin()应用插件,"this"关键字将在插件函数内引用您调用插件的jquery对象。
因此,总结一下:
(function($){ $.fn.myPlugin = function(){ if(this.size()> 1){ //多个元素的代码 } else if(this.size()== 1){ //一个元素的代码 } } })(jQuery); $('div.to-pluginize').myPlugin();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接