【问题标题】:Interacting with jQuery plugin objects after their creation创建后与 jQuery 插件对象交互
【发布时间】:2010-09-25 15:09:36
【问题描述】:

我有一个使用轮询更新哪些项目的代码。我为ticker编写了一个简单的jQuery插件,调用方式如下:

$("#cont ul").ticker();

这将一个 ul 变成一个股票行情,在 li 中滚动。要添加新项目,我必须将 lis 添加到 ul,这很好。但是,我的 OO 希望我可以在代码对象上添加一个 addItem 函数。但是,我不想失去 jQuery 使用的可链接性。

有没有比添加 ul 更明显但又符合 jQuery 做事方式的方法?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    jQuery 并不是真正的 OO 解决方案,所以你说它不是真正的“jQuery 方式”是正确的。我听说 Prototype 完全是关于 OO 的,所以有一天你可能想研究一下。

    您没有理由不能向 jQuery 对象添加另一个函数:

    $.fn.addTickerItem = function(contents) {
        this.append(
            $("<li></li>").html(contents);
        );
        return this;
    };
    

    ..但你会慢慢污染命名空间。

    【讨论】:

      【解决方案2】:

      你应该做的是扩展插件的设置:

      jQuery.ticker = function(settings)
      {
      var settings = 
      jQuery.extend(
      {
      action : 'create',
      item : $(this)
      }
      ,settings);
      
      return $(this).each(function(){
      if(settings.action =='create')
      {
        //initialize ticker..
      }
      else if(settings.action == 'add')
      {
        //add to ticker.
      }
      }//end each.
      }//end plugin.
      
      $('#ticker').ticker(); //this will initialize it, no problem.
      
      var settings1 = { action : 'add', item : $(expr1) }
      $('#ticker').ticker(settings1);//this will execute the "add" action.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-25
        • 1970-01-01
        相关资源
        最近更新 更多