如何创建一个返回另一个对象的jQuery函数?
问题描述:
我创建的jQuery插件:如何创建一个返回另一个对象的jQuery函数?
$.fn.myGrid = function() {
return ???;
}
我想要的myGrid
返回值包括附加功能,让我可以在下面的方式来使用它;
var grid = $(".myGrid").myGrid();
grid.add();
我该怎么做?我如何声明添加函数?我还有什么要返回myGrid
插件?
我也很高兴有这样的作品;
$.myGrid.add();
这可能吗?
答
一个你可以使用的方法是this;
$.fn.myGrid = function() {
var that = this;
return {
add: function() {
that.after('<h2>Here I am, adding something'); // Note `that` rather than `this`.
},
remove: function() {
that.next().remove();
}
};
}
捕捉this
变量是很重要的,因为否则从myGrid()
函数的对象,你return
上的方法将无法访问您的调用myGrid()
jQuery对象。
请参阅此处的操作代码; http://jsfiddle.net/HpeS8/
答
通常情况下,写了一个插件,最好的约定是这样的:
$.fn.pluginName = function(){
// return the same object to preserve chainability
// and also apply the plugin's functionality to all the
// dom elements in this jquery collection
return this.each(function(i,el){
// do whatever you want with $(el)
});
};
如果你正在写返回,而不是在某种程度上当前对象(比如像width
作品操纵值插件),你应该返回值,而不是当前对象的引用(this
):
$.fn.maxWidth = function(){
var max = 0;
this.each(function(i,el){
var w = $(el).width();
if(w > max)
max = w;
});
return max;
};
如果你想给用户访问&修改的可能性哟你应该保持链接性(我的意思是返回this
而不是包含你插件的api的其他对象),并通过jQuery元素的data
方法向用户公开插件的API。
下面是一个例子。让我们说我们正在制作一个视频播放器jquery插件。我们希望保持链接性,但仍然能够访问此插件的核心功能。
做到这一点的正确的方式将是这样的:
$.fn.videoPlayer = function(){
var api = {
play : function(){/*...*/},
pause : function(){/*...*/},
stop : function(){/*...*/}
};
return this.each(function(i,el){
$(el).data('videoPlayerApi',api);
});
};
的使用示例这表明我的观点:
$('video')
// initialising the plugin
.videoPlayer()
// the return value is the original jQuery object,
// so we can still call jQuery methods on it
.css('opacity',1)
// select the first video
.eq(0)
// access the first video's plugin api
.data('videoPlayerApi')
// start only the first video
.start();
答
(function ($) {
var methods = {
init: function() {
//Initilize
},
var add = {
//Do something
}
$.fn.myGrid= function (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 exist on jQuery.myGrid'); }
};
})(jQuery);
这样调用
var grid = $(".myGrid").myGrid();
grid.myGrid("add");