【问题标题】:jQuery Boilerplate passing element as optionjQuery Boilerplate 将元素作为选项传递
【发布时间】:2012-12-31 15:48:15
【问题描述】:

我使用 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>

为什么这两个 3 console.log(this.options.nextElem) 没有返回我的 jQuery 对象?

【问题讨论】:

标签: jquery jquery-plugins plugins


【解决方案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();
}

【讨论】:

  • @nicolast - 就像我说的,您正在调用document.ready 上的插件,但是您的主闭包内(您的类之外)的任何代码都会立即运行。
  • @nicolast - 不。这只是为你的局部变量创建了一个闭包,但它会立即运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 2011-02-17
  • 2011-07-15
  • 2010-12-02
相关资源
最近更新 更多