0

jquery 1.9.1 を使用しており、プラグインを開発しようとしています。問題は、プラグインが機能していないことです。コードは次のとおりです。

    ;(function($) {

    $.fn.single = function() {

        return this.each(function(){

            // Get the instance
            var element = $(this);

            // Resize the "data-target" divs
            element.load(function(){
                changeCSS(element);
            });

            // Bind the method to the resize window event
            $(window).bind("resize", function(){  
                changeCSS(element);  
            });

        });

    };

    // function to resize all the "data-target" divs
    function changeCSS(element) {

        // Grab the screen resolution
        var windowWidth     = $(window).width();
        var windowHeight    = $(window).height();
        // Count how many targets the div has
        var targetsSize     = $("[data-target]").size();

        // Resize the parent div
        $(element).css({
            "width" : windowWidth,
            "height": windowHeight * targetsSize
        });

        // Resize all the targets div
        $(element + "> div[data-target]").each(function(){
            $(this).css({
                "width" : windowWidth,
                "height": windowHeight
            });
        });

    }

})(jQuery);

そして、私はそのようにドキュメントでそれを呼び出しています:

<script src="js/jquery-1.9.1.min.js"></script>
    <script src="js/single-0.1.0.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#single").single();
        });
    </script>

コンソールに問題はありません。私が間違っていることは何ですか?

4

3 に答える 3

2

メソッド.loadを誤用しているためだと思います。jQuery docs を見ると、次のことを目的としています。

.load() : サーバーからデータをロードし、返された HTML を一致した要素に配置します。

http://api.jquery.com/load/

行を削除しelement.load(function ...、単に changeCSS 関数を呼び出します。この拡張機能は既に Document.Ready にロードされています。

    return this.each(function () {
        // ...

        changeCSS(element); // <-- just run the function right away

        // ... etc
    });
于 2013-03-25T18:07:26.840 に答える
0

一般に、宣言する前に関数を呼び出すのは悪い習慣です。プラグインを正しく作成するには、最初から正しく構造化することをお勧めします。それに加えて、@mcpDESIGNS が指摘しているように、.load メソッドを間違って使用しいます。また、ここで加担しようとしていることを正確に説明すると便利です。

jQuery プラグインの作成を開始するには、ここで jQuery のドキュメントを参照するか、このチュートリアルを参照してください。

これは好ましい構造です:

(function($) {

  // Declare your methods at the beginning of your plugin
  var yourMethods = {
    'methodOne' : function() {

    },
    'methodTwo' : function() {

    }
  };

  $.fn.pluginName = function() {

    return this.each(function() {

    });

  }
}(jQuery));
于 2013-03-25T18:37:13.660 に答える
0

それ以外の:

element.load(function(){
    changeCSS(element);
});

やった:

changeCSS(element);

そして...代わりに:

$(element + "> div[data-target]")

やった:

$(element).children('div[data-target]')

そして今、プラグインはバグやエラーなしで実行されています. みんなありがとう!

于 2013-03-26T14:13:30.893 に答える