如果我扩展jquery fn(如$.fn.extend),我会编写我的插件:
(function($){
$.fn.extend({
functionName : function(){
//function returns
return this.each(function(){
$(this).append("<div>text</div>");
});
}
});
})(jQuery);当我想扩展jQuery命名空间时,我会这样写:
(function($){
$.extend({
functionName : function(){
//function returns
}
});
})(jQuery);我不知道的是在这种情况下如何编写“return”
发布于 2009-12-14 09:11:02
更新
当您执行涉及多个选择器的多个操作时,您必须决定哪个操作最有意义。如果一个选择器是主要焦点,但也影响其他项,则像插件一样编写它,并返回主要结果集,如下所示:
$.fn.myAction = function(secondarySelector){
return this.each(function(){
$(this).css('display', 'block');
$(secondarySelector).hide();
});
};
// Use:
// $(primarySelector).myAction(secondarySelector);
$("#id").myAction(".address"); // Chain continues after action如果选择器的重要性相同,那么只需创建一个不返回任何内容的函数,或者根据成功情况返回true / false。
另一种构建代码的方式:
extend方法在其他OOP框架中使用,如您所示,它也可以与jQuery一起使用。但是,您会发现许多jQuery开发人员选择了更短、更明显的语法,例如:
(function($){
// The if statement allows the file to be used with
// other files that use the same shared namespace
if(!$.Namespace){
$.Namespace = { };
};
$.Namespace.Constructor = function( params ){
... code ...
};
// And for the wrapper sets ($.fn):
$.fn.functionName = function(opts){
return this.each(function(){
... code ...
});
};
})(jQuery);发布于 2009-12-14 08:53:38
您可以在第二个实例中返回您喜欢的任何内容。例如,考虑$.each()与$.get()的对比。但是,如果我是您,我会避免将其用作函数命名空间-它可能会导致污染。相反,您应该将此保留为在jquery名称空间下添加您自己的名称空间,如下所示:
(function($){
$.extend({
myNamspace : {
functionName: function(){
// return whatever
}
}
}});
})(jQuery);https://stackoverflow.com/questions/1898402
复制相似问题