大佬教程收集整理的这篇文章主要介绍了javascript – 如何使jQuery插件函数可以单独使用,不能在集合上运行,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
// example usage of my to-be-created plugin function // this is the way described in the docs,and I kNow how to do that $("a").MyFunction () // but I also want to be able to call the function without a collection: $.MyFunction ();
如果在没有要操作的集合的情况下调用$.MyFunction(),它将创建它自己的要匹配的元素集合 – 一种初始化过程(但不一定只运行一次).此外,$.MyFunction()应保持可链接性.
我想要实现的伪代码:
// [...] function MyFunction (): { if (notCalledOnACollection) { // this should run when called via $.MyFunction () $elements = $("a.myClass"); } else { $elements = $(this); } return $elements.each (function () { // do sth. here }); }
我真的希望将所有函数实现/功能保留在单个函数定义中,并且在jQuery对象中的两个单独位置中没有两个单独命名的函数或两个同名函数.
当然我可以添加一个参数MyFunction(do_init)来指示要执行的if语句的哪个分支,但这会使我的参数列表混乱(我想对多个插件使用该方法,并且会有MyFunction()的参数为了简单起见我刚刚离开这里.
有什么好建议吗?
(function( $) { $.myPlugin = $.fn.myPlugin = function(myPluginArguments) { if(this.jquery) //"this" is a jquery collection,do jquery stuff with it } else { //"this" is not a jquery collection } }; $.fn.myPlugin.otherFunc = function() { }; })( jQuery );
这里唯一的区别是$.myPlugin = part,它允许你直接调用你的插件而不运行jquery的选择器函数.如果您确定需要其他功能或属性,可以将它们创建为插件的属性.
用法:
//using a SELEctor (arguments optional) $("@L_969_30@meClass").myPlugin(); //using the options variable - or whatever your arguments are $.myPlugin({id: "somEID"}); //accessing your other functions/properties $.myPlugin.otherFunc();
以上是大佬教程为你收集整理的javascript – 如何使jQuery插件函数可以单独使用,不能在集合上运行全部内容,希望文章能够帮你解决javascript – 如何使jQuery插件函数可以单独使用,不能在集合上运行所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。