0

以下代码将创建一个带有方法的插件

(function ( $ ) {

    $.fn.greenify = function( options ) {

        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            color: "#556b2f",
            backgroundColor: "white"
        }, options );

        // Greenify the collection based on the settings variable.
        return this.css({
            color: settings.color,
            backgroundColor: settings.backgroundColor
        });

    };

}( jQuery ));

我们可以这样使用:

$( "div" ).greenify({
    color: "orange"
});

但我想知道这样的事情

<div class="pluginclass"></div>

然后这应该是根据插件在标记中使用类但不喜欢$('div').pluginclass();

4

1 回答 1

0

因此,您不想创建需要由用户调用的函数,而是只想在与您的 CSS 类匹配的所有 div 上运行一个函数?这与编写任何普通的 jQuery 脚本没有什么不同:

(function ( $ ) {
    var settings = { color: "white", backgroundColor: "green" };
    $(".pluginclass").each(function() {
        // Do work
    };
    // Greenify the collection based on the settings variable.
    $(".pluginclass").css({
        color: settings.color,
        backgroundColor: settings.backgroundColor
    });

}( jQuery ));

一旦您在页面上包含上述内容,所有.pluginclassdiv 的背景都将设置为绿色,颜色设置为白色。

于 2013-10-24T11:51:17.530 回答