javascript - 具有多种方法的 jQuery 插件

标签 javascript jquery jquery-plugins plugins

我将以一种很好的方式包装我的一些函数,为此我想使用 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/

相关文章:

Javascript,按顺序执行脚本代码插入dom树

jquery - 如何按内容日期对 div 进行排序

javascript - 菜单切换类打开不起作用

jquery - 向 jsTree 添加 jQuery 自定义图像工具提示

javascript - 编写 jquery 代码来检查复选框是否被选中并指示选中的复选框数?

javascript - 如何使用按钮清除 localStorage?

javascript - 大型react-redux表单应用程序

javascript - 禁用 jquery 日期选择器中的先前日期

jquery - 在jquery中编写onclick事件的适当位置

javascript - 是否有关于从浏览器启动 Adob​​e AIR 应用程序的教程?