0

好吧,我知道,标题可能听起来有点奇怪......

以下问题:

我有一个这样的jquery函数:

(function($){
    $.fn.myFunction = function(opts){
        var settings = {
           params: {}
        };
    }

    if ( options ) { 
      $.extend( settings, options );
    }

}

现在,该函数应用于这样的元素:

$('#elem').myFunction({'data':'test','data2': 'test2'});

如何从函数外部访问设置属性?

意思是,在函数初始化后,我想更改一些设置 - 但我不知道如何。

有任何想法吗?

(希望我写的内容不会太混乱:)

4

1 回答 1

1

You'll have to take the variable up into higher level scope.

(function ($) {

    // we expose your variable up here
    var settings = {
    };

    $.fn.myFunction = function (opts) {
        // ...instead of down here
        // do something with settings, like:
        opts = $.extend({}, settings, opts);
    }

    // you can then access a "shared" copy of your variable even here
    if (options) {
        $.extend(settings, options);
    }

})(jQuery);

If you have to expose it further, you'll just have to work along that same gist.

As a side note however, do note that calling $.extend(settings, options) will modify the settings variable. A nice way to do the same thing without modifying the original settings value is to call $.extend() on an empty object, and just cache the return like I did in the first $.extend() call in my example.

var modified_options = $.extend({}, settings, options);
于 2012-08-23T13:25:29.167 回答