插件方法声明 - 无法使其工作

时间:2011-07-06 03:26:32

标签: javascript jquery jquery-plugins

我一直在努力解决使用插件在一个对象上提供方法的正确语法。这是基本框架:

<!DOCTYPE html>
<html>
<head>
<!-- jQuery -->
<script type="text/javascript" src="http://goo.gl/XQPhA"></script>
<script type="text/javascript">
(function($) {
    $.test = function(el, options) {
        this.whiten = function() {
            $(this).css('background-color', options.bg);
        }
    };
    $.test.settings = {
        bg: 'white'
    };
    $.fn.test = function(options) {
        options = $.extend(options, $.test.settings);
        return this.each(function() {
            $.test(this, options);
        });
    };
})(jQuery);

$(document).ready(function() {
    $('#list').test().css('background-color', 'wheat');
    $('#go').click(function() {
        $('#list').whiten();
    });
});
</script>
</head>

<body>
<button id="go">whiten</button>
<ul id="list">
<li>Aloe</li>
<li>Bergamot</li>
<li>Calendula</li>
<li>Damiana</li>
<li>Elderflower</li>
<li>Feverfew</li>
</ul>
</body>
</html>

我觉得我不确定如何进行功能分配。 this内的$.test将引用包含在我的列表中的jQuery对象,因此我认为this.myMethod = function() {会有效,但事实并非如此。 $(this)将是一个双包装器,el是我的列表(我不想将该方法直接分配给该对象,因为我无法像这样调用它:{{1 }})和$('#list').whiten()$(el)相同......那么这是怎么做到的?

- 更新 -

我创建了一个[jsfiddle]来解决问题

- 更新 -

我也尝试将该方法放在$(this)函数中但无效

2 个答案:

答案 0 :(得分:0)

试试这个:

 $.fn.test = function(options) {        
   options = $.extend(options, $.test.settings);      
   var self = this;  
   return this.each(function() {
        $.test(self, options);
    });
};

答案 1 :(得分:0)

在多次哭泣和咬牙切齿之后,我想通了。我不确定我理解它为什么会这样,但是现在我很开心它!

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://goo.gl/XQPhA"></script>
<script type="text/javascript">
(function($) {
    $.test = {
        bg: 'white'
    };

    $.fn.test = function(options) {
        options = $.extend({}, $.test, options);

        this.whiten = function() {
            $(this).css('background-color', options.bg);
        };

        return this.each(function() {
            $.fn.test(options);
        });
    };
})(jQuery);

$(document).ready(function() {
    $('#list').test().css('background-color', 'wheat');
    $('#go').click(function() {
        $('#list').whiten();
    });
});
</script>
</head>

<body>
<button id="go">whiten</button>
<ul id="list">
<li>Aloe</li>
<li>Bergamot</li>
<li>Calendula</li>
<li>Damiana</li>
<li>Elderflower</li>
<li>Feverfew</li>
</ul>
</body>
</html>