如何将插件中的以下属性/变量转换为可以从文档准备好设置的默认值和选项?
//插件js:
(function($){
$.fn.myPlugin = function(options){
var myForm = this;
myForm.variable1 = true;
myForm.variable2 = true;
myForm.variable3 = true;
myForm.variable4 = true;
...
if(myForm.variable1){
// do something
}
...
}
})(jQuery);
//在页面中准备好文档:
<script type="text/javascript">
$(document).ready(function() {
$('#form1').myPlugin();
});
</script>
答案 0 :(得分:17)
最简单的模式是扩展默认选项对象。但它确实意味着任何参数必须作为“选项”对象一起传递,例如:myPlugin({variable2:false})
(function($){
$.fn.myPlugin = function(options){
var defaults = {
variable1 : true,
variable2 : true,
variable3 : true,
variable4 : true
}
var settings = $.extend({}, defaults, options);
...
if(settings.variable1){
// do something
}
...
}
})(jQuery);
答案 1 :(得分:0)
见以下内容:
$('#form1').myPlugin({variable1 : true, variable2: false....});
并使用
(function($){
$.fn.myPlugin = function(options){
options.variable1 = true;
options.variable2 = true;
options.variable3 = true;
options.variable4 = true;
}
})(jQuery);
正确方法见
http://jquery-howto.blogspot.com/2009/01/how-to-set-default-settings-in-your.html