如何在jquery插件中启用选择器

时间:2014-11-20 19:11:03

标签: jquery jquery-plugins

假设我写了一个jquery插件(它所做的就是在所选元素上使文本变为红色),如下所示:

jQuery.fn.testPlugin = function(options){
    // default plugin settings
    settings = jQuery.extend({
        el: 'p'

    }, options);

    $(function () {

        $(settings.el).css('color', 'red');

    }); // end ready

} // end jQuery.fn.testPlugin

然后,说我有一个<p>,我想把它涂成红色,我会这样称呼我的插件:

$().testPlugin('p');

我不知道并希望知道的是,如何让选择器在$()内工作,以便我可以执行以下操作并获得相同的效果,而不需要el在设置内。

$('p').testPlugin();

1 个答案:

答案 0 :(得分:0)

通常this将返回当前选择器:

jQuery.fn.testPlugin = function(options){
  return this.each(function(){
    //having code here assigns like you wanted : $('p').testPlugin();
    $(this).css('color', 'red');
  });
};

现在,你可以申请:

$('p').testPlugin();

但是,既然你想要两种方式:

只需使用以下方式:

jQuery.fn.testPlugin = function(options){
    // code you're having and below code:
    if(settings.el == undefined){
       return this.each(function(){
           //rest of my above code
      });
   }
} // end jQuery.fn.testPlugin