简体   繁体   English

jQuery插件有多种方法

[英]jQuery plugin with multiple methods

I am going to wrap some of my functions in a nice manner and for this I want to go with jQuery approach. 我将以一种很好的方式包装我的一些函数,为此我想采用jQuery方法。 Like jQuery having a lots of methods 就像jQuery有很多方法一样

$.parseJson()
$.ajax()
$("div").text("hey my testing");

and both methods are present in a same jQuery file. 并且这两种方法都存在于同一个jQuery文件中。 But while reading about how to make a jquery plugin, its specified that you don't need to create multiple functions inside a same plugin. 但在阅读有关如何制作jquery插件的过程中,它指定您不需要在同一个插件中创建多个函数。 Instead pass an argument which contains the method name as string. 而是将包含方法名称的参数传递为字符串。

So, Is that the below snippet is correct or do i need to make some corrections in it. 那么,下面的代码片段是正确的还是我需要对其进行一些更正。

<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>

The second way is preferred because it conserves namespace in the jQuery object. 第二种方式是首选,因为它保留了jQuery对象中的命名空间。

Read the official jQuery doc for this: Plugins/Authoring 阅读官方jQuery文档: 插件/创作

Have you try using jquery boilerplate . 你尝试过使用jquery样板吗? It is a good point to start study jQuery plugin development. 开始研究jQuery插件开发是一个很好的观点。 It's provide a safe and(seem to be) a good solution to create a plugin. 它提供了一个安全的(似乎是)创建插件的好解决方案。 They use your second way to call a method. 他们使用您的第二种方式来调用方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM