【问题标题】:Detect if jQuery plugin is applied to multiple elements?检测jQuery插件是否应用于多个元素?
【发布时间】:2011-04-15 16:55:12
【问题描述】:

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

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

编辑...

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

有没有办法在第二个例子中使用插件时检测多个实例/

【问题讨论】:

  • 我添加了一种方法来做到这一点......但请记住,当它在第一个元素上调用时,计数将为 1,你无法知道它会应用于更多之后的元素。

标签: javascript jquery events jquery-plugins jquery-animate


【解决方案1】:

插件里面的this,根据你的风格,指的是jQuery对象,所以你可以检查the .length property,例如:

 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)

【讨论】:

    【解决方案2】:

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

    所以,总结一下:

    (函数($){ $.fn.myPlugin = function() { 如果(this.size()> 1){ //多个元素的代码 } 否则 if(this.size() == 1) { //1个元素的代码 } } })( jQuery ); $('div.to-pluginize').myPlugin();

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-12
        • 2013-11-07
        相关资源
        最近更新 更多