![](/img/trans.png)
[英]How to create a Jquery Plugin with Plugin Methods and Maintaining Chainability?
[英]How to create a jQuery plugin with methods?
我正在嘗試編寫一個 jQuery 插件,它將為調用它的對象提供額外的功能/方法。 我在網上看的所有教程(過去2小時一直在瀏覽)最多包括如何添加選項,而不是附加功能。
這是我想要做的:
//通過調用該div的插件將div格式化為消息容器
$("#mydiv").messagePlugin();
$("#mydiv").messagePlugin().saySomething("hello");
或類似的規定。 歸結為:我調用插件,然后調用與該插件關聯的函數。 我似乎找不到辦法做到這一點,而且我以前見過很多插件都這樣做。
到目前為止,這是我對插件的了解:
jQuery.fn.messagePlugin = function() {
return this.each(function(){
alert(this);
});
//i tried to do this, but it does not seem to work
jQuery.fn.messagePlugin.saySomething = function(message){
$(this).html(message);
}
};
我怎樣才能實現這樣的目標?
謝謝!
2013 年 11 月 18 日更新:我已經更改了 Hari 以下評論和贊成票的正確答案。
根據 jQuery 插件創作頁面 ( http://docs.jquery.com/Plugins/Authoring ),最好不要混淆 jQuery 和 jQuery.fn 命名空間。 他們建議這種方法:
(function( $ ){
var methods = {
init : function(options) {
},
show : function( ) { },// IS
hide : function( ) { },// GOOD
update : function( content ) { }// !!!
};
$.fn.tooltip = function(methodOrOptions) {
if ( methods[methodOrOptions] ) {
return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
// Default to "init"
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.tooltip' );
}
};
})( jQuery );
基本上,您將函數存儲在一個數組中(作用域為包裝函數),如果傳遞的參數是一個字符串,則檢查一個條目,如果參數是一個對象(或 null),則恢復為默認方法(此處為“init”)。
然后你可以像這樣調用方法......
$('div').tooltip(); // calls the init method
$('div').tooltip({ // calls the init method
foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method
Javascripts“arguments”變量是傳遞的所有參數的數組,因此它適用於任意長度的函數參數。
這是我用來創建帶有附加方法的插件的模式。 你會像這樣使用它:
$('selector').myplugin( { key: 'value' } );
或者,直接調用一個方法,
$('selector').myplugin( 'mymethod1', 'argument' );
例子:
;(function($) {
$.fn.extend({
myplugin: function(options,arg) {
if (options && typeof(options) == 'object') {
options = $.extend( {}, $.myplugin.defaults, options );
}
// this creates a plugin for each element in
// the selector or runs the function once per
// selector. To have it do so for just the
// first element (once), return false after
// creating the plugin to stop the each iteration
this.each(function() {
new $.myplugin(this, options, arg );
});
return;
}
});
$.myplugin = function( elem, options, arg ) {
if (options && typeof(options) == 'string') {
if (options == 'mymethod1') {
myplugin_method1( arg );
}
else if (options == 'mymethod2') {
myplugin_method2( arg );
}
return;
}
...normal plugin actions...
function myplugin_method1(arg)
{
...do method1 with this and arg
}
function myplugin_method2(arg)
{
...do method2 with this and arg
}
};
$.myplugin.defaults = {
...
};
})(jQuery);
這種方法怎么樣:
jQuery.fn.messagePlugin = function(){
var selectedObjects = this;
return {
saySomething : function(message){
$(selectedObjects).each(function(){
$(this).html(message);
});
return selectedObjects; // Preserve the jQuery chainability
},
anotherAction : function(){
//...
return selectedObjects;
}
};
}
// Usage:
$('p').messagePlugin().saySomething('I am a Paragraph').css('color', 'red');
選定的對象存儲在 messagePlugin 閉包中,該函數返回一個包含與插件關聯的函數的對象,在每個函數中,您可以對當前選定的對象執行所需的操作。
您可以在此處測試和使用代碼。
編輯:更新代碼以保留 jQuery 鏈接能力的強大功能。
當前選擇的答案的問題是你實際上並沒有像你認為的那樣為選擇器中的每個元素創建自定義插件的新實例......你實際上只是創建一個實例並傳入選擇器本身作為范圍。
查看此小提琴以獲得更深入的解釋。
相反,您需要使用jQuery.each遍歷選擇器並為選擇器中的每個元素實例化自定義插件的新實例。
這是如何做:
(function($) {
var CustomPlugin = function($el, options) {
this._defaults = {
randomizer: Math.random()
};
this._options = $.extend(true, {}, this._defaults, options);
this.options = function(options) {
return (options) ?
$.extend(true, this._options, options) :
this._options;
};
this.move = function() {
$el.css('margin-left', this._options.randomizer * 100);
};
};
$.fn.customPlugin = function(methodOrOptions) {
var method = (typeof methodOrOptions === 'string') ? methodOrOptions : undefined;
if (method) {
var customPlugins = [];
function getCustomPlugin() {
var $el = $(this);
var customPlugin = $el.data('customPlugin');
customPlugins.push(customPlugin);
}
this.each(getCustomPlugin);
var args = (arguments.length > 1) ? Array.prototype.slice.call(arguments, 1) : undefined;
var results = [];
function applyMethod(index) {
var customPlugin = customPlugins[index];
if (!customPlugin) {
console.warn('$.customPlugin not instantiated yet');
console.info(this);
results.push(undefined);
return;
}
if (typeof customPlugin[method] === 'function') {
var result = customPlugin[method].apply(customPlugin, args);
results.push(result);
} else {
console.warn('Method \'' + method + '\' not defined in $.customPlugin');
}
}
this.each(applyMethod);
return (results.length > 1) ? results : results[0];
} else {
var options = (typeof methodOrOptions === 'object') ? methodOrOptions : undefined;
function init() {
var $el = $(this);
var customPlugin = new CustomPlugin($el, options);
$el.data('customPlugin', customPlugin);
}
return this.each(init);
}
};
})(jQuery);
和一個工作小提琴。
您會注意到在第一個小提琴中,所有 div 總是向右移動完全相同的像素數。 這是因為選擇器中的所有元素都只存在一個選項對象。
使用上面寫的技術,您會注意到在第二個小提琴中,每個 div 都沒有對齊並且隨機移動(第一個 div 除外,因為它的隨機發生器在第 89 行始終設置為 1)。 那是因為我們現在正確地為選擇器中的每個元素實例化了一個新的自定義插件實例。 每個元素都有自己的選項對象,並且不保存在選擇器中,而是保存在自定義插件本身的實例中。
這意味着您將能夠從新的 jQuery 選擇器訪問在 DOM 中的特定元素上實例化的自定義插件的方法,並且不會像您在第一個小提琴中那樣被迫緩存它們。
例如,這將使用第二個小提琴中的技術返回所有選項對象的數組。 它首先會返回 undefined 。
$('div').customPlugin();
$('div').customPlugin('options'); // would return an array of all options objects
這就是您必須訪問第一個小提琴中的選項對象的方式,並且只會返回一個對象,而不是它們的數組:
var divs = $('div').customPlugin();
divs.customPlugin('options'); // would return a single options object
$('div').customPlugin('options');
// would return undefined, since it's not a cached selector
我建議使用上面的技術,而不是當前選擇的答案中的技術。
使用jQuery UI 小部件工廠。
例子:
$.widget( "myNamespace.myPlugin", {
options: {
// Default options
},
_create: function() {
// Initialization logic here
},
// Create a public method.
myPublicMethod: function( argument ) {
// ...
},
// Create a private method.
_myPrivateMethod: function( argument ) {
// ...
}
});
初始化:
$('#my-element').myPlugin();
$('#my-element').myPlugin( {defaultValue:10} );
方法調用:
$('#my-element').myPlugin('myPublicMethod', 20);
(這就是jQuery UI庫的構建方式。)
一種更簡單的方法是使用嵌套函數。 然后您可以以面向對象的方式鏈接它們。 例子:
jQuery.fn.MyPlugin = function()
{
var _this = this;
var a = 1;
jQuery.fn.MyPlugin.DoSomething = function()
{
var b = a;
var c = 2;
jQuery.fn.MyPlugin.DoSomething.DoEvenMore = function()
{
var d = a;
var e = c;
var f = 3;
return _this;
};
return _this;
};
return this;
};
下面是如何稱呼它:
var pluginContainer = $("#divSomeContainer");
pluginContainer.MyPlugin();
pluginContainer.MyPlugin.DoSomething();
pluginContainer.MyPlugin.DoSomething.DoEvenMore();
不過要小心。 在創建嵌套函數之前,您不能調用它。 所以你不能這樣做:
var pluginContainer = $("#divSomeContainer");
pluginContainer.MyPlugin();
pluginContainer.MyPlugin.DoSomething.DoEvenMore();
pluginContainer.MyPlugin.DoSomething();
DoEvenMore 函數甚至不存在,因為尚未運行創建 DoEvenMore 函數所需的 DoSomething 函數。 對於大多數 jQuery 插件,您實際上只會有一層嵌套函數,而不是我在這里展示的兩層。
只需確保在創建嵌套函數時,在執行父函數中的任何其他代碼之前,在父函數的開頭定義這些函數。
最后,請注意“this”成員存儲在名為“_this”的變量中。 對於嵌套函數,如果需要在調用客戶端中引用實例,則應返回“_this”。 您不能只在嵌套函數中返回“this”,因為那樣會返回對函數的引用而不是 jQuery 實例。 返回 jQuery 引用允許您在返回時鏈接內部 jQuery 方法。
我從jQuery Plugin Boilerplate得到它
在jQuery Plugin Boilerplate 中也有描述,reprise
// jQuery Plugin Boilerplate
// A boilerplate for jumpstarting jQuery plugins development
// version 1.1, May 14th, 2011
// by Stefan Gabos
// remember to change every instance of "pluginName" to the name of your plugin!
(function($) {
// here we go!
$.pluginName = function(element, options) {
// plugin's default options
// this is private property and is accessible only from inside the plugin
var defaults = {
foo: 'bar',
// if your plugin is event-driven, you may provide callback capabilities
// for its events. execute these functions before or after events of your
// plugin, so that users may customize those particular events without
// changing the plugin's code
onFoo: function() {}
}
// to avoid confusions, use "plugin" to reference the
// current instance of the object
var plugin = this;
// this will hold the merged default, and user-provided options
// plugin's properties will be available through this object like:
// plugin.settings.propertyName from inside the plugin or
// element.data('pluginName').settings.propertyName from outside the plugin,
// where "element" is the element the plugin is attached to;
plugin.settings = {}
var $element = $(element), // reference to the jQuery version of DOM element
element = element; // reference to the actual DOM element
// the "constructor" method that gets called when the object is created
plugin.init = function() {
// the plugin's final properties are the merged default and
// user-provided options (if any)
plugin.settings = $.extend({}, defaults, options);
// code goes here
}
// public methods
// these methods can be called like:
// plugin.methodName(arg1, arg2, ... argn) from inside the plugin or
// element.data('pluginName').publicMethod(arg1, arg2, ... argn) from outside
// the plugin, where "element" is the element the plugin is attached to;
// a public method. for demonstration purposes only - remove it!
plugin.foo_public_method = function() {
// code goes here
}
// private methods
// these methods can be called only from inside the plugin like:
// methodName(arg1, arg2, ... argn)
// a private method. for demonstration purposes only - remove it!
var foo_private_method = function() {
// code goes here
}
// fire up the plugin!
// call the "constructor" method
plugin.init();
}
// add the plugin to the jQuery.fn object
$.fn.pluginName = function(options) {
// iterate through the DOM elements we are attaching the plugin to
return this.each(function() {
// if plugin has not already been attached to the element
if (undefined == $(this).data('pluginName')) {
// create a new instance of the plugin
// pass the DOM element and the user-provided options as arguments
var plugin = new $.pluginName(this, options);
// in the jQuery version of the element
// store a reference to the plugin object
// you can later access the plugin and its methods and properties like
// element.data('pluginName').publicMethod(arg1, arg2, ... argn) or
// element.data('pluginName').settings.propertyName
$(this).data('pluginName', plugin);
}
});
}
})(jQuery);
為時已晚,但也許有一天它可以幫助某人。
我遇到了同樣的情況,用一些方法創建了一個 jQuery 插件,在閱讀了一些文章和一些輪胎之后,我創建了一個 jQuery 插件樣板( https://github.com/acanimal/jQuery-Plugin-Boilerplate )。
此外,我用它開發了一個管理標簽的插件( https://github.com/acanimal/tagger.js ),並寫了兩篇博客文章逐步解釋了 jQuery 插件的創建( https://www. acuriousanimal.com/blog/20130115/things-i-learned-creating-a-jquery-plugin-part-i )。
你可以做:
(function($) {
var YourPlugin = function(element, option) {
var defaults = {
//default value
}
this.option = $.extend({}, defaults, option);
this.$element = $(element);
this.init();
}
YourPlugin.prototype = {
init: function() { },
show: function() { },
//another functions
}
$.fn.yourPlugin = function(option) {
var arg = arguments,
options = typeof option == 'object' && option;;
return this.each(function() {
var $this = $(this),
data = $this.data('yourPlugin');
if (!data) $this.data('yourPlugin', (data = new YourPlugin(this, options)));
if (typeof option === 'string') {
if (arg.length > 1) {
data[option].apply(data, Array.prototype.slice.call(arg, 1));
} else {
data[option]();
}
}
});
};
});
通過這種方式,您的插件對象將作為數據值存儲在您的元素中。
//Initialization without option
$('#myId').yourPlugin();
//Initialization with option
$('#myId').yourPlugin({
// your option
});
// call show method
$('#myId').yourPlugin('show');
使用觸發器怎么樣? 有誰知道使用它們有什么缺點嗎? 好處是所有內部變量都可以通過觸發器訪問,而且代碼非常簡單。
請參閱jsfiddle 。
<div id="mydiv">This is the message container...</div>
<script>
var mp = $("#mydiv").messagePlugin();
// the plugin returns the element it is called on
mp.trigger("messagePlugin.saySomething", "hello");
// so defining the mp variable is not needed...
$("#mydiv").trigger("messagePlugin.repeatLastMessage");
</script>
jQuery.fn.messagePlugin = function() {
return this.each(function() {
var lastmessage,
$this = $(this);
$this.on('messagePlugin.saySomething', function(e, message) {
lastmessage = message;
saySomething(message);
});
$this.on('messagePlugin.repeatLastMessage', function(e) {
repeatLastMessage();
});
function saySomething(message) {
$this.html("<p>" + message + "</p>");
}
function repeatLastMessage() {
$this.append('<p>Last message was: ' + lastmessage + '</p>');
}
});
}
在這里,我想建議創建帶有參數的簡單插件的步驟。
(function($) { $.fn.myFirstPlugin = function(options) { // Default params var params = $.extend({ text: 'Default Title', fontsize: 10, }, options); return $(this).text(params.text); } }(jQuery)); $('.cls-title').myFirstPlugin({ text: 'Argument Title' });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1 class="cls-title"></h1>
在這里,我們添加了名為params
的默認對象,並使用extend
函數設置了選項的默認值。 因此,如果我們傳遞空白參數,那么它將設置默認值,否則它將設置。
閱讀更多:如何創建 JQuery 插件
試試這個:
$.fn.extend({
"calendar":function(){
console.log(this);
var methods = {
"add":function(){console.log("add"); return this;},
"init":function(){console.log("init"); return this;},
"sample":function(){console.log("sample"); return this;}
};
methods.init(); // you can call any method inside
return methods;
}});
$.fn.calendar() // caller or
$.fn.calendar().sample().add().sample() ......; // call methods
這是我的基本版本。 與之前發布的類似,您可以這樣調用:
$('#myDiv').MessagePlugin({ yourSettings: 'here' })
.MessagePlugin('saySomething','Hello World!');
- 或者直接訪問實例plugin_MessagePlugin
$elem = $('#myDiv').MessagePlugin();
var instance = $elem.data('plugin_MessagePlugin');
instance.saySomething('Hello World!');
MessagePlugin.js
;(function($){
function MessagePlugin(element,settings){ // The Plugin
this.$elem = element;
this._settings = settings;
this.settings = $.extend(this._default,settings);
}
MessagePlugin.prototype = { // The Plugin prototype
_default: {
message: 'Generic message'
},
initialize: function(){},
saySomething: function(message){
message = message || this._default.message;
return this.$elem.html(message);
}
};
$.fn.MessagePlugin = function(settings){ // The Plugin call
var instance = this.data('plugin_MessagePlugin'); // Get instance
if(instance===undefined){ // Do instantiate if undefined
settings = settings || {};
this.data('plugin_MessagePlugin',new MessagePlugin(this,settings));
return this;
}
if($.isFunction(MessagePlugin.prototype[settings])){ // Call method if argument is name of method
var args = Array.prototype.slice.call(arguments); // Get the arguments as Array
args.shift(); // Remove first argument (name of method)
return MessagePlugin.prototype[settings].apply(instance, args); // Call the method
}
// Do error handling
return this;
}
})(jQuery);
以下插件結構利用 jQuery- data()
-方法為內部插件方法/設置提供公共接口(同時保留 jQuery 鏈接能力):
(function($, window, undefined) {
const defaults = {
elementId : null,
shape : "square",
color : "aqua",
borderWidth : "10px",
borderColor : "DarkGray"
};
$.fn.myPlugin = function(options) {
// settings, e.g.:
var settings = $.extend({}, defaults, options);
// private methods, e.g.:
var setBorder = function(color, width) {
settings.borderColor = color;
settings.borderWidth = width;
drawShape();
};
var drawShape = function() {
$('#' + settings.elementId).attr('class', settings.shape + " " + "center");
$('#' + settings.elementId).css({
'background-color': settings.color,
'border': settings.borderWidth + ' solid ' + settings.borderColor
});
$('#' + settings.elementId).html(settings.color + " " + settings.shape);
};
return this.each(function() { // jQuery chainability
// set stuff on ini, e.g.:
settings.elementId = $(this).attr('id');
drawShape();
// PUBLIC INTERFACE
// gives us stuff like:
//
// $("#...").data('myPlugin').myPublicPluginMethod();
//
var myPlugin = {
element: $(this),
// access private plugin methods, e.g.:
setBorder: function(color, width) {
setBorder(color, width);
return this.element; // To ensure jQuery chainability
},
// access plugin settings, e.g.:
color: function() {
return settings.color;
},
// access setting "shape"
shape: function() {
return settings.shape;
},
// inspect settings
inspectSettings: function() {
msg = "inspecting settings for element '" + settings.elementId + "':";
msg += "\n--- shape: '" + settings.shape + "'";
msg += "\n--- color: '" + settings.color + "'";
msg += "\n--- border: '" + settings.borderWidth + ' solid ' + settings.borderColor + "'";
return msg;
},
// do stuff on element, e.g.:
change: function(shape, color) {
settings.shape = shape;
settings.color = color;
drawShape();
return this.element; // To ensure jQuery chainability
}
};
$(this).data("myPlugin", myPlugin);
}); // return this.each
}; // myPlugin
}(jQuery));
現在您可以使用以下語法調用內部插件方法來訪問或修改插件數據或相關元素:
$("#...").data('myPlugin').myPublicPluginMethod();
只要您從myPublicPluginMethod()
的實現內部返回當前元素 (this),jQuery-chainability 就會被保留——因此以下工作:
$("#...").data('myPlugin').myPublicPluginMethod().css("color", "red").html("....");
以下是一些示例(有關詳細信息,請查看此小提琴):
// initialize plugin on elements, e.g.:
$("#shape1").myPlugin({shape: 'square', color: 'blue', borderColor: 'SteelBlue'});
$("#shape2").myPlugin({shape: 'rectangle', color: 'red', borderColor: '#ff4d4d'});
$("#shape3").myPlugin({shape: 'circle', color: 'green', borderColor: 'LimeGreen'});
// calling plugin methods to read element specific plugin settings:
console.log($("#shape1").data('myPlugin').inspectSettings());
console.log($("#shape2").data('myPlugin').inspectSettings());
console.log($("#shape3").data('myPlugin').inspectSettings());
// calling plugin methods to modify elements, e.g.:
// (OMG! And they are chainable too!)
$("#shape1").data('myPlugin').change("circle", "green").fadeOut(2000).fadeIn(2000);
$("#shape1").data('myPlugin').setBorder('LimeGreen', '30px');
$("#shape2").data('myPlugin').change("rectangle", "red");
$("#shape2").data('myPlugin').setBorder('#ff4d4d', '40px').css({
'width': '350px',
'font-size': '2em'
}).slideUp(2000).slideDown(2000);
$("#shape3").data('myPlugin').change("square", "blue").fadeOut(2000).fadeIn(2000);
$("#shape3").data('myPlugin').setBorder('SteelBlue', '30px');
// etc. ...
這實際上可以使用defineProperty
以“不錯”的方式工作。 其中“nice”意味着不必使用()
來獲取插件命名空間,也不必通過字符串傳遞函數名稱。
兼容性 nit: defineProperty
在 IE8 及以下版本的舊瀏覽器中不起作用。 警告: $.fn.color.blue.apply(foo, args)
不起作用,您需要使用foo.color.blue.apply(foo, args)
。
function $_color(color)
{
return this.css('color', color);
}
function $_color_blue()
{
return this.css('color', 'blue');
}
Object.defineProperty($.fn, 'color',
{
enumerable: true,
get: function()
{
var self = this;
var ret = function() { return $_color.apply(self, arguments); }
ret.blue = function() { return $_color_blue.apply(self, arguments); }
return ret;
}
});
$('#foo').color('#f00');
$('#bar').color.blue();
根據 jquery 標准,您可以按如下方式創建插件:
(function($) {
//methods starts here....
var methods = {
init : function(method,options) {
this.loadKeywords.settings = $.extend({}, this.loadKeywords.defaults, options);
methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
$loadkeywordbase=$(this);
},
show : function() {
//your code here.................
},
getData : function() {
//your code here.................
}
} // do not put semi colon here otherwise it will not work in ie7
//end of methods
//main plugin function starts here...
$.fn.loadKeywords = function(options,method) {
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 ecw-Keywords');
}
};
$.fn.loadKeywords.defaults = {
keyName: 'Messages',
Options: '1',
callback: '',
};
$.fn.loadKeywords.settings = {};
//end of plugin keyword function.
})(jQuery);
怎么調用這個插件?
1.$('your element').loadKeywords('show',{'callback':callbackdata,'keyName':'myKey'}); // show() will be called
參考:鏈接
我想這可能對你有幫助......
(function ( $ ) { $.fn.highlight = function( options ) { // This is the easiest way to have default options. var settings = $.extend({ // These are the defaults. color: "#000", backgroundColor: "yellow" }, options ); // Highlight the collection based on the settings variable. return this.css({ color: settings.color, backgroundColor: settings.backgroundColor }); }; }( jQuery ));
在上面的示例中,我創建了一個簡單的 jQuery突出顯示插件。我分享了一篇文章,其中我討論了如何創建自己的 jQuery 插件,從基礎到高級。 我認為您應該檢查一下... http://mycodingtricks.com/jquery/how-to-create-your-own-jquery-plugin/
下面是一個小插件,有調試目的的警告方法。 將此代碼保存在 jquery.debug.js 文件中:JS:
jQuery.fn.warning = function() {
return this.each(function() {
alert('Tag Name:"' + $(this).prop("tagName") + '".');
});
};
HTML:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src = "jquery.debug.js" type = "text/javascript"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").warning();
$("p").warning();
});
</script>
</head>
<body>
<p>This is paragraph</p>
<div>This is division</div>
</body>
</html>
這是我的操作方法:
(function ( $ ) {
$.fn.gridview = function( options ) {
..........
..........
var factory = new htmlFactory();
factory.header(...);
........
};
}( jQuery ));
var htmlFactory = function(){
//header
this.header = function(object){
console.log(object);
}
}
您所做的基本上是通過新方法擴展jQuery.fn.messagePlugin 對象。 這很有用,但對您而言不是。
你所要做的就是使用這種技術
function methodA(args){ this // refers to object... }
function saySomething(message){ this.html(message); to first function }
jQuery.fn.messagePlugin = function(opts) {
if(opts=='methodA') methodA.call(this);
if(opts=='saySomething') saySomething.call(this, arguments[0]); // arguments is an array of passed parameters
return this.each(function(){
alert(this);
});
};
但是你可以完成你想要的我的意思是有一種方法可以做到 $("#mydiv").messagePlugin().saySomething("hello"); 我的朋友,他開始寫有關 lugin 的文章以及如何使用您的功能鏈擴展它們,這里是他博客的鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.