如何让函数变量像jquery插件一样被调用?
插件:
(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 );
我想这样调用 mymethod:
$('.element').mymethod();
这可能吗?
基本上它需要保持链接,以便我可以进一步调用其他函数......
Plugin:
(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 );
I want to call mymethod like this:
$('.element').mymethod();
Is this possible?
Basically it needs to keep the chaining so I can further call other functions...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您还没有这样做,我强烈建议您查看 jQuery 插件创作页面。 http://docs.jquery.com/Plugins/Authoring
调用特定方法的最佳方式 )
实现类似目标的方式将是这样的,(注意:全部取自 jQuery 插件创作网站
If you haven't already done so, I would highly recommend checking out the jQuery plugin authoring page. http://docs.jquery.com/Plugins/Authoring
The best way to call a specific method would be by going
The way you would achieve something like that would be like this, ( note: all taken from the jQuery plugin authoring site )
如果您想像 jQuery 插件一样调用它,您将无法将其添加到 jQuery 原型 ($.fn)。但是,如果您只想让 this 引用选择器的 jQuery 元素,您可以使用 应用:
If you want to call it like a jQuery plugin you will have no way around adding it to the jQuery prototype ($.fn). But if you just want to have this reference the jQuery element of your selector you can just use apply:
关闭,只要有新的
function
关键字,您就会丢失this
关键字。首先尝试保存它:Close, you just lose the
this
keyword whenever there's a newfunction
keyword. Try saving it first:好吧,那么您只需这样做:
jQuery 将自动将其调用的元素作为
this
传递。但以这种方式添加大量功能被认为是不好的做法。这就是为什么大多数插件只是向
$.fn
添加一个函数,并采用一个字符串参数来调用哪个方法。Well, then you'd just do:
jQuery will automatically pass the element it's called on as
this
.But it's considered bad practice to add lots of functions this way. That's why most plugins just add one function to
$.fn
and take a string argument for which method to call.更改 MyMethod,使其成为直接扩展
更新 x2(有一个拼写错误)!
http://jsfiddle.net/MattLo/2TWMV/1/
Alter MyMethod so its a direct extension
Updated x2 (had a typo)!
http://jsfiddle.net/MattLo/2TWMV/1/