繁体   English   中英

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

[英]Detect if jQuery plugin is applied to multiple elements?

我正在研究一个可以应用于多个元素的jQuery插件。 该插件包含一些动画效果,我需要根据插件是否用于多个元素(而不是一个)来管理事件队列。

检测插件是否已应用于单个元素或多个元素的最佳方法是什么?

编辑...

如果插件传递了多个元素(例如$('.myClass').plugin() ),那么length属性可以正常工作,但是如果插件是在多个单个元素上调用的(例如$('#myElem1').plugin()$('#myElem2').plugin() )然后长度为每个调用返回一个。

是否有一种方法可以在使用插件时检测多个实例,如第二个示例中所示/

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)

假设您通过$('some selector')。myPlugin()应用插件,“this”关键字将引用您在插件函数内调用插件的jquery对象。

所以,总结一下:

(function( $ ){
  $.fn.myPlugin = function() {
    if(this.size() > 1) {
       //code for multiple elements
    }
    else if(this.size() == 1) {
       //code for 1 element
    }
  }
})( jQuery );

$('div.to-pluginize').myPlugin();

如果您想要一种通用的方法来测试插件是否已应用于任意元素集,这里有一种方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM