2013-02-08 89 views
0


例如我有jQuery插件,我調用一個init方法,像這樣一些atrributes:如何更改jQuery插件的屬性

jQuery(document).ready(function($) { 
    $('#someid').somePlugin({ 
          animation : 'fadeIn', 
          speed : '1000', 
          easing : 'swing' 
         }); 
}); 

讓我們假設我還有頁面上的HTML鏈接。是否有可能以某種方式通過點擊html鏈接來改變這個插件的init函數的屬性值?
所以,通過點擊鏈接我想改變速度屬性,而不刷新頁面。如果可能,實施這一行動的最佳方式是什麼?

或者我應該先改變插件代碼中的內容。 插件的代碼:

(function($) { 
    $.fn.extend({ 
     somePlugin: function(options) { 

      var defaults = { 
       speed : 500, 
       animation : 'fadeIn', 
       easing : false 
      } 

      var options = $.extend(defaults, options); 
      var speed = options.speed; 
      var easing = options.easing; 
      var animation = options.animation; 

      return this.each(function() { 
       var obj = $(this); 
       //some action here 
      }); 
     } 
    }); 
})(jQuery); 
+1

這完全取決於插件的寫法!傳遞一個新對象或傳遞字符串,就像你說的jQuery UI等等,如果插件不支持它,它也不起作用。 – adeneo 2013-02-08 22:28:41

+0

@adeneo,你應該將其作爲答案發布,因爲其他人不完整或者只是不正確。 – Sparky 2013-02-08 23:13:27

回答

-1

是的,你可以做這樣的:

$('#someid').somePlugin('option', 'animation', 5000); 

此外,您可以一次通過更改多個選項:

$('#someid').somePlugin('option', {animation: 5000, otherOption: 'blah'}); 

我應該提到這只是適用於某些如果您使用「官方」jQuery插件。很多插件作者都堅持這種設計模式,但並非都是這樣。另外,如果您使用jQuery UI Widget Factory開發插件,則可免費獲得此功能。


編輯:由於OP正在創作他自己的插件,我們可以展示如何利用自定義插件來促進此功能的示例。直接從jQuery plugin authoring page取得:

(function($){ 
    var methods = { 
    init : function(options) { 
     //Extend options here with your 
     //defaults and init your plugin 
    }, 
    option: function(key, value){ 
     options[key] = value; 
    } 
    }; 

    $.fn.somePlugin = function(method) { 
    // Method calling logic 
    if (methods[method]) { 
     return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
    } else if (typeof method === 'object' || ! method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     //some error that method doesnt exist 
    }  

    }; 

})(jQuery); 

$('div').somePlugin({someOption: true}); 
//..later 
$('div').somePlugin('option', 'someOption', false); 
+0

** Quote:** _「...只有**才能確定**如果您使用」**官方**「jQuery插件」_〜一個「官方」jQuery插件? [沒有這種東西](http://docs.jquery.com/Plugins/Authoring)。 jQuery和jQueryUI開發團隊成員JörnZaefferer編寫的[jQuery Validate插件](http://bassistance.de/jquery-plugins/jquery-plugin-validation/)甚至沒有這種能力:http ://jsfiddle.net/Lqpjy/ – Sparky 2013-02-08 22:57:55

+0

我想我應該說的官方「jQuery UI」插件?更好?僅僅因爲某人是jQuuery開發團隊的成員並且他們創建了一個插件,並不意味着該插件是「正式」的。這些是由jQuery UI團隊官方支持和記錄的插件:http://api.jqueryui.com/category/widgets/。 – joeltine 2013-02-08 22:58:12

+0

是的,一致認爲,除非有某種認證過程,否則任何插件都不能成爲「官方」。由於該問題不是專門針對jQueryUI,或者提到jQueryUI,所以您的觀點是沒有意義的。 – Sparky 2013-02-08 22:59:09