0

プラグインパターンとしてjQueryボイラープレートを使用しています。jQueryボイラープレート
の詳細については、https ://github.com/jquery-boilerplate/boilerplate/を参照してください。

デフォルトオプションとして要素を渡したいのですが、
ここではアクセスできません(簡略化された)コードです:

;(function ( $, window, document, undefined ) {

    /*creating the default settings*/
    var pluginName = 'pluginName',
        defaults = {
            nextElem:$('#right') 
        };
    console.log(defaults.nextElem); // return : Object[] , not cool

    /*merging default and options, then calling init*/
    function Plugin( element, options ) {
        this.options = $.extend( {}, defaults, options);
        this.init();
    }
    Plugin.prototype = {
        init: function() {
            /*trying to access the default nextElem */
            console.log(this.options.nextElem); // return : Object[] , not cool
            console.log(this._defaults.nextElem); // return : Object[] , not cool
            this.options.nextElem = $('#right');
            console.log(this.options.nextElem);// return : Object[div#right] , cool
        }
    };

    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
            }
        });
    }
})( jQuery, window, document );

とHTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <script type="text/javascript" src="js/jquery1.8.3.js"></script>
        <script type="text/javascript" src="js/pluginName.js"></script>
    </head>
    <body>
    <script>
    $(function(){
        $('#img').PluginName();
    });
    </script>
    <div id="img"></div>
    <div id="right"></div>
    </body>
</html>

2つの3console.log(this.options.nextElem)がjQueryオブジェクトを返さないのはなぜですか?

4

1 に答える 1

1

以前にプラグインのコードを実行しているようですdocument.ready

ドキュメントの準備ができてからプラグイン関数を呼び出すだけですが、プラグイン関数自体その前に実行されます。への最初の呼び出し$('#right')は、の前に行われdocument.readyます。


別のアプローチは、実際のオブジェクトの代わりに文字列を渡すことです。

var pluginName = 'pluginName',
    defaults = {
        nextElem: '#right'
    };

function Plugin( element, options ) {
    this.options = $.extend( {}, defaults, options);
    this.options.nextElem = $(this.options.nextElem);
    this.init();
}
于 2012-12-31T15:50:41.743 に答える