我将以一种很好的方式包装我的一些函数,为此我想使用 jQuery 方法。就像 jQuery 有很多方法
$.parseJson()
$.ajax()
$("div").text("hey my testing");
并且这两种方法都存在于同一个 jQuery 文件中。但是在阅读如何制作 jquery 插件时,它指定您不需要在同一个插件中创建多个函数。相反,传递一个包含方法名称作为字符串的参数。
那么,下面的代码片段是否正确,或者我是否需要对其进行一些更正。
<script type="text/javascript">
(function ($) {
$.fn.testMethod1 = function () {
return $(this).each(function () { });
};
$.fn.testMethod2 = function () {
return $(this).each(function () { });
};
$.test = function () {
return "testresult"
};
})(jQuery);
$("div1").testMethod1();
$("div2").testMethod2();
$.test();
//Is that needed to be replace in a different way like
$("div1").myPlugin("testMethod1");
$("div1").myPlugin("testMethod2");
$("div1").myPlugin("test");
</script>
最佳答案
第二种方式是首选,因为它保留了 jQuery 对象中的命名空间。
阅读官方 jQuery 文档:Plugins/Authoring
关于javascript - 具有多种方法的 jQuery 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15287126/