如何使函数变量像jquery插件一样被调用
How to make a function variable be called like jquery plugins?
插件:
(function( $ ){
$.fn.myplugin = function( options ) {
var mymethod = function(){
// I want to be able to access "this" here ('.element')
return this;
};
return this.each(function() {
// $('.element', this).mymethod(); <- how to do this?
});
};
})( jQuery );
我想这样调用我的方法:
$('.element').mymethod();
这可能吗?
基本上,它需要保持链接,这样我就可以进一步调用其他函数。。。
如果您还没有这样做,我强烈建议您查看jQuery插件创作页面。http://docs.jquery.com/Plugins/Authoring
调用特定方法的最佳方法是进行
$( '#foo' ).myPlugin( 'myMethod' );
实现类似目标的方法是这样的,(注意:所有内容都来自jQuery插件创作网站)
( function ( $ ) {
var methods = {
init : function( options ) {
// Init function here
},
destroy : function( ) {
// Teardown function here
}
};
$.fn.myPlugin= 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.myPlugin' );
}
};
})( jQuery );
如果你想像jQuery插件一样调用它,你将无法将其添加到jQuery原型($.fn)中。但如果你只想让this引用选择器的jQuery元素,你可以使用apply:
(function( $ ){
$.fn.myplugin = function( options ) {
var mymethod = function(){
// I want to be able to access "this" here ('.element')
return this;
};
return this.each(function() {
mymethod.apply($('.element', this));
});
};
})( jQuery );
关闭时,只要有新的function
关键字,就会丢失this
关键字。尝试先保存:
(function( $ ){
$.fn.myplugin = function( options ) {
var that = this;
var mymethod = function(_this, dotElem){
// I want to be able to access "this" here ('.element')
that.hide().blah()...
return this; // this isn't needed as we are going to anyway return `this.each()`
};
return this.each(function() {
mymethod(this, $('.element' )); <- how to do this?
});
};
})( jQuery );
好吧,那么你只需要做:
$.fn.mymethod = function () { ... return this; }
jQuery将自动将其调用的元素传递为this
。
但是以这种方式添加大量函数被认为是不好的做法。这就是为什么大多数插件只在$.fn
中添加一个函数,并为调用哪个方法使用字符串参数的原因。
更改MyMethod,使其成为的直接扩展
$.fn.mymethod = function() {
this.hide(); // the .element
return this; // continue the daisy chain
}
// example usage
$(document).ready(function() {
$("div").mymethod();
});
更新了x2(有一个打字错误)!
http://jsfiddle.net/MattLo/2TWMV/1/
相关文章:
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- D3在一个调用中绘制不同的SVG形状,没有可见性
- Dijkstra's”;针对GOTO声明的案件“;与函数一样适用于现代调用代码的命名封装
- 我怎么能像调用synch方法一样调用async方法呢
- 如何使pjax:postate像一个简单的pjax调用一样工作
- 有人可以解释我如何像我五岁一样进行 JSONP 调用
- PHP call_user_func像 Javascript 调用一样绑定这个 Arg
- 如何像jquery一样自动调用Javascript中的函数
- 在 JavaScript 中调用函数,就像在 JQuery 中一样
- 原型链接、调用父方法的行为就像父构造函数从未运行过一样
- D3 示例:看起来像一个 JavaScript 变量,但像一个函数一样调用
- 当javascript函数更改html输入文本时,我希望输入文本像调用其他JS函数一样触发事件
- 如何使函数变量像jquery插件一样被调用
- 异步执行某个东西,就像将它推到调用堆栈的后面一样
- 如何实现像jQuery一样的链式方法调用
- 如何在c++中动态调用属性名,就像JS中的方括号符号一样
- 是否有可能使一个对象在Javascript中调用时像函数一样
- 如何使javascript对象像函数一样被调用
- JavaScript像jQuery一样调用变量作为对象和函数
- 调用像函数一样声明的对象