代码之家  ›  专栏  ›  技术社区  ›  ICR

创建jQuery插件对象后与之交互

  •  2
  • ICR  · 技术社区  · 17 年前

    我有一个使用轮询更新项目的自动收报机。我为ticker编写了一个简单的jQuery插件,其调用方式如下:

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

    这将一个ul变成一个滚动的滚动条。要添加新项目,我必须将lis添加到ul中,这很好。然而,我内心的OO希望我能在ticker对象上有一个addItem函数。但是,我不想失去jQuery使用的可链接性。

    是否有某种方法比将ul添加到列表中更明显,但符合jQuery的做事方式?

    2 回复  |  直到 17 年前
        1
  •  5
  •   Andrew Theken Tan Li Hau    17 年前

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

    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.
    
        2
  •  1
  •   nickf    17 年前

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

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

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

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