Jquery 如何调用插件方法
这是我的插件代码Jquery 如何调用插件方法,jquery,Jquery,这是我的插件代码 (function( $ ) { $.fn.myGrid = function(options) { var _myGrid = this; var _$myElement; var setOutTimer; var settings = $.extend({ url: null, dataType: "json", colName
(function( $ ) {
$.fn.myGrid = function(options) {
var _myGrid = this;
var _$myElement;
var setOutTimer;
var settings = $.extend({
url: null,
dataType: "json",
colNames: []
}, options );
this.initiateGRID = function(that) {
_$myElement = $(that);
}
this.showInlineSuccess = function(msg){
//Some Code
}
return this.each(function() {
_myGrid.initiateGRID(this);
});
};
}( jQuery ));
加载插件后,我想从外部调用showInlineSuccess方法,比如$.myGrid.showInlineSuccess('Hello')代码>
如何实现这一点?使用以下方法:
$.fn.myGrid.showInlineSuccess('Hello')代码>
而不是:
$.myGrid.showInlineSuccess('Hello')代码>
您缺少fn
您应该像这样设计它
(function( $ ) {
function Grid(options) {
this._myGrid = null,
this._$myElement = null,
// other properties of grid
}
// add methods to Grid class
Grid.prototype = {
initiateGRID : function(that) {
var grid = this;
grid._$myElement = $(that);
},
howInlineSuccess : function(msg){
//Some Code
}
}
$.fn.myGrid = function(options) {
var settings = $.extend({
url: null,
dataType: "json",
colNames: []
}, options );
return new Grid(settings)
}
}( jQuery ));
var grid = $('some selector').myGrid()
grid.showInlineSuccess('Hello')
现在你可以这样称呼它
(function( $ ) {
function Grid(options) {
this._myGrid = null,
this._$myElement = null,
// other properties of grid
}
// add methods to Grid class
Grid.prototype = {
initiateGRID : function(that) {
var grid = this;
grid._$myElement = $(that);
},
howInlineSuccess : function(msg){
//Some Code
}
}
$.fn.myGrid = function(options) {
var settings = $.extend({
url: null,
dataType: "json",
colNames: []
}, options );
return new Grid(settings)
}
}( jQuery ));
var grid = $('some selector').myGrid()
grid.showInlineSuccess('Hello')
如果你想这样称呼它
var grid = $.myGrid()
grid.showInlineSuccess('Hello')
然后将插件定义更改为
$.myGrid = function(options) { // code
这会给你你所需要的,但不要认为这是最好的方法
$.fn.myGrid().showInlineSuccess('asdfasdfasdf');
请注意,myGridTypeError之后的()错误:无法调用unfineine的方法'showInlineSuccess',这不是最好的方法,因为它会再次创建一个对象