如何从另一个 javascript 文件初始化插件

How to initialize a plugin from another javascript file

我有以下fiddle。单击按钮 'scroll',是否可以调用插件内的 scrollTest 函数?现在我再次调用整个 test() ,因此每次我单击滚动按钮时它都会创建一个新的测试对象。

我的代码[fiddle demo]

    (function ($, win, doc) {
    'use strict';

    $.fn.test = Plugin;
    $.fn.test.Constructor = Test;

    function Plugin() {
        return this.each(function () {
            new Test(this);
        });
    }

    // TREE CLASS DEFINITION
    // =====================
    function Test(el) {
         var publ = this,
            priv = {};
        console.log("start");
        $('.test_button').click(function(){
            console.log("clicked");
            publ.scrollTest
        })

         publ.scrollTest = function () {
            console.log("in scrolltest");
        };
        publ.bindEvents= function () {
            console.log("in bind");
        };
        publ.fileter= function () {
            console.log("in filter");
        };
    }
    }(jQuery, this, this.document));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <h2>Hello</h2>
    <button class="test_button">Click me</button>
    <button class="test_button2" onclick="$('h2').test()">scroll</button>
    </body>
    <script>
 $('h2').test();
    </script>

您需要将它的使用包装在一个 $(document).ready(); 块中,以确保脚本在开始使用之前已加载。

如果您希望您的代码 运行 onClick 具有 class [=37 的元素=] 你可以使用:

// include this only ONCE on your page.
$(document).ready(function() {
   $(this).test(true); // sends the flag to initialize the click() event once
   $('.test_button2').click(function(){
       $(this).test(); // action on every .test_button2 click();
   });
});

.. 并替换 ..

<button class="test_button2" onclick="$('h2').test()">scroll</button>

..与..

<button class="test_button2">scroll</button>

请参阅下面的代码以了解正在执行的修复:

(function ($, win, doc) {
    'use strict';

    $.fn.test = Plugin;

    var publ, priv;

    function Plugin(initialize) {
        if(initialize === true) {
           console.log("start");
           $('.test_button').click(function(){
              console.log("clicked");
           });
        }
        console.log("in scrolltest");
    }

    }(jQuery, this, this.document));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <h2>Hello</h2>
    <button class="test_button">Click me</button>
    
    <!-- onClick is handled by jQuery's .click() method -->
    <button class="test_button2">scroll</button>
</body>
<script>
   // this code should only be placed once on your page.
  
   var $test;
  
   $(document).ready(function() {
      $test = $(this).test(true);
      $('.test_button2').click(function(){
         $(this).test();
      });
   });
</script>