如何访问插件中的一个链接函数



如何访问插件中的一个链接函数?

这是我的插件,其中我需要在文档上返回一个附加元素。

(function($){
        $.fn.extend({ 
            selection: function(options) {
                var defaults = {
                    element:     "selection"
                }
                var options =  $.extend(defaults, options);
                var o = options;
                var $this = this;

               $this.function_1 = function(object)
                {
                    alert('function 1');
                }
                $this.function_2 = function(object)
                {
                    alert('function 2');
                }
                $(document.body).append("<div class='element'>Loading</div>");
                var element = $('.element');
                return element;
            }
        });
    })(jQuery);​

当点击按钮时,它应该提醒"功能2",但它在firefox上返回错误。

下面是我的jsffidle,

http://jsfiddle.net/dm3ft/

一种方法是向插件函数添加一个参数,以字符串形式传递方法。基础知识取自jQuery插件创作文档:

(function($) {
    var methods = {
        function_1: function(object) {
            alert('function 1');
        },
        function_2: function(object) {
            alert('function 2');
        }
    };

$.fn.selection = function(method, options) {
    return this.each(function(){
        $(this).click(function() {
              // Method calling logic
               if (methods[method]) {
                   return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
               } else if (typeof method === 'object' || !method) {
                   return methods.init.apply(this, arguments);
               } else {
                   $.error('Method ' + method + ' does not exist on jQuery.tooltip');
               }
          });
    });
})(jQuery);

然后调用插件方法:

  $('.chain-function').selection('function_2'/* optional options object*/);

演示:http://jsfiddle.net/dm3ft/1/

注意:重要的是,您要意识到插件函数中的this是DOM元素,不要将其与作为类的一部分的this混淆

您也可以使用jQuery.fn

$(document).ready(function(){
   $('.chain-function').function_2();
});
(function($){
    $.fn.function_2 = function(object){
        alert("yay!");
        var element = $("<div />").addClass("element").text("Loading");
        element.appendTo(  $(document.body) );
        return element;
    };
})(jQuery);​

最新更新