gpt4 book ai didi

javascript - 如何让函数变量像jquery插件一样被调用?

转载 作者:行者123 更新时间:2023-11-28 11:39:34 24 4
gpt4 key购买 nike

插件:

(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 );

关于javascript - 如何让函数变量像jquery插件一样被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8965712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com