在函数外部访问jQuery脚本

时间:2013-04-24 21:07:32

标签: jquery

我激活了一个像这样的jQuery脚本:

$('#an-id').drawbox();

这是jQuery脚本(重要部分):

(function($)
{
$.fn.extend(
{
    drawbox: function()
    {

        // Default options
        var defaults = {
            caption:       'Caption',
            // Canvas properties
            lineWidth:     3,
            lineCap:       'round',
            lineJoin:      'round',
            miterLimit:    10,
            strokeStyle:   'green',
            fillStyle:     'none',
            shadowOffsetX: 0.0,
            shadowOffsetY: 0.0,
            shadowBlur:    0.0,
            shadowColor:   'none',
        }

        options = $.extend(defaults);

        return this.each(function()
        {

            //etc

脚本运行正常,但我想稍后在单独的脚本中获取'options'值。我猜测选项设置已设置并存储在函数中,可以在以后检索。

我尝试过这样的事情:

$('#an-id').drawbox.options

......但似乎无法得到它。

3 个答案:

答案 0 :(得分:1)

查找

(function($) {
    $.fn.yourPlugin = function(options) {
         options= jQuery.extend({ opt: 1, opt2: 2 }, options);
         // the escope of your plugin....
    }
})(jQuery);

您需要通过参数获取选项,并将param选项与属性默认值合并,使用options属性覆盖默认属性,或者如果选项为空则提取默认值

答案 1 :(得分:1)

drawbox是一个函数,因此该行无效:

$('#an-id').drawbox.options

并且每次调用$('#an-id').drawbox()都会执行不正确的代码。

您必须在构造函数方法中使用参数,以便您可以返回像这样的选项

$('#an-id').drawbox('options')

看一下手风琴的实现,我认为它可以满足您的需求:

http://api.jqueryui.com/accordion/#method-option

答案 2 :(得分:1)

你有drawbox()方法,但似乎你现在设置它只执行一个内部函数。要做你想做的事,你必须设置你的插件以允许多种方法......

执行此操作的一般jquery approved方法是将所有方法都包含在插件代码中的methods object中,其中函数init是您的默认函数,就像这样。 ..

var methods = {
  "getOptions" : function(){ return options; },

  "init" : function(){
    return this.each(function(){
      //your current code goes here (what happens when you call $().drawbox)
    });
  }
}

现在,您必须包含以下代码或类似内容,以使您的插件调用您想要的方法...

  $.fn.drawbox = function(method){
    if(methods[method]){
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    }else if(!methods[method]){
      return methods.init.apply(this, arguments);
    }else{
      $.error('Method ' +  method + ' does not exist on jQuery.drawbox');
    }      
  };  

注意这是做什么的。调用.drawbox()时,执行上述操作,如果未传递参数,则调用init函数。如果传递了参数,例如drawbox('getOptions'),则执行getOptions方法(在方法对象中)。

通过这种方式,您可以返回插件范围内的任何变量,其概念类似于普通的getter / setter。您还需要删除当前代码中的行drawbox : function(){...,因为上面的代码将替换它。

相关问题