调用jQuery插件而不指定selcetor

时间:2016-05-19 15:21:41

标签: jquery

我正在尝试制作一个小插件来更改页面上的主要和辅助颜色。

现在,当你指定一个选择器时它正在工作,但我正在尝试解决这个问题

我的代码:

(function($) {

$.fn.Color = function( options ) {

    // Establish our default settings
     var settings = $.extend({
        primary_color           : null,
        secondary_color         : null
    }, options);

    return this.each( function() {

        if ( settings.primary_color ) {

            $(".primary_color").css( 'color', settings.primary_color);
            $(".bg-primary_color").css( 'color', settings.primary_color);
        }

        if ( settings.secondary_color  ) {
            $(".secondary_color").css( 'color', settings. secondary_color);
        }
    });

};

}(jQuery));

在页面中我添加了这个:

$('h1').Color({
  primary_color  : '#000',
  secondary_color : '#fff' 
});

1 个答案:

答案 0 :(得分:1)

jQuery真的被设计用于元素。最聪明的做法是传入一个选择器,并设计你的插件将自己限制在该选择器的范围内:

(function($) {

$.fn.Color = function( options ) {

    // Establish our default settings
     var settings = $.extend({
        primary_color           : null,
        secondary_color         : null
    }, options);

    return this.each( function() {

        if ( settings.primary_color ) {

            $(".primary_color", this).css( 'color', settings.primary_color);
            $(".bg-primary_color", this).css( 'color', settings.primary_color);
        }

        if ( settings.secondary_color  ) {
            $(".secondary_color", this).css( 'color', settings. secondary_color);
        }
    });

};

}(jQuery));

然后,在调用时选择合适的选择器。如果您确实希望页面上的所有内容都应用此样式,请使用body

$('body').Color({
  primary_color  : '#000',
  secondary_color : '#fff' 
});

这种方法的优点是,如果将来需求发生变化,您可以将行为范围缩小到其他元素。

如果您不想将这些效果限定为特定元素,那么jQuery插件可能不是正确的方法。为什么不直接声明Color函数?这会简单得多。

Color({
  primary_color  : '#000',
  secondary_color : '#fff' 
});

作为最后一点,我应该指出,这个特定的用例(基于类选择器更改颜色)最好留给CSS,而不是JavaScript。最简单的方法就是使用CSS样式:

.primary_color { color: #000 }
.secondary_color { color: #fff }

因此,除非您需要动态更改这些颜色的具体原因,否则我将完全避免为此制作插件。