2

我像这样激活一个 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

该脚本运行良好,但我想稍后在单独的脚本中获取“选项”值。我猜选项设置已设置并存储在函数中,以后可以检索。

我试过这样的事情:

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

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

4

3 回答 3

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(){...当前代码中的行,因为上面替换了它。

于 2013-04-24T21:22:30.347 回答
1

看:

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

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

于 2013-04-24T21:19:22.183 回答
1

drawbox 是一个函数,所以这一行是无效的:

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

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

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

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

看看手风琴的实现,我认为它做了一些你需要的事情:

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

于 2013-04-24T21:20:54.317 回答