2012-10-12 42 views
5

我寫了一個簡單的jQuery插件,但我想,使其更加先進,所以我可以做這樣的事情:

$.myplugin.close(); 
$.myplugin.open(); 
$.myplugin.next(); 
$.myplugin.prev(); 

我如何可以編寫一個插件,可以這樣調用?

-------------------------更新-------------------- -----

Thanks @Craig MacGregor,非常感謝。

但將它需要像下面

$(this).myplugin.load(); 
+2

這是不好的格式,絕不應該b e就是這樣建造的。所有的函數都應該作爲方法來訪問,比如$('ele')。myplugin('close/open/next/prev'); – Ohgodwhy

+2

這麼多upvotes ...奇怪。 – gdoron

+0

@Ohgodwhy如果我需要設置我的選項更詳細,那麼我需要寫爲 '$('。ele')。myplugin({action:'close',xxx:xxx ......}) ; 「 – user1740052

回答

3

您可以將對象分配給 「爲myplugin」 像這樣的功能:

$.myplugin = { 
    close: function(){ 
     //code 
    }, 
    open: function(){ 
     //code 
    }, 
    next: function(){ 
     //code 
    }, 

    prev: function(){ 
     //code 
    } 
}; 
2

只是一個例子:

(funciton($) { 
    var methods = { 
    init: function() {}, 
    close: function() {}, 
    open: function() {}, 
    prev: function() {}, 
    next: function() {}, 
    }; 

    $.fn.myplugin = function (method) { 
    if (methods[method]) { 
     return methods[method].apply(this, [].slice.call(arguments, 1)); 
    } else if (typeof method == 'object' || !method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     $.error('Method ' + method + ' does not exist on myplugin'); 
    }  
    }; 

}(jQuery)); 

//usage 
$(selector).myplugin(); 

// call methods 
$(selector).myplugin('close'); 
$(selector).myplugin('open'); 
$(selector).myplugin('next'); 
$(selector).myplugin('prev');