我正在尝试创建一个能够在初始化后更新选项的插件。我从简单的插件开始,这将帮助我理解插件的逻辑。所以这里是:
;(function($) {
var defaults = {
message: 'This is default message'
};
var options = {};
var methods = {
init : function( options ) {
options = $.extend(defaults, options);
return this.each(function() {
$(this).click(function(){
alert(options.message);
});
});
},
option: function( key, value ){
if (val) {
options[key] = val;
} else {
return options[key];
}
}
};
$.fn.clickAlert = function( method ) {
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);
如您所见,该插件仅显示带有定义文本的警报消息。 另外,我有 HTML 页面(其中包含 jquery 库和此插件),其中有 2 个链接:
<a href="#" class="show">SHOW ALERT</a>
<a href="#" class="change">CHANGE ALERT MESSAGE</a>
我在“show”类的链接上创建了“clickAlert”插件的实例。当我单击它时,它会按我的预期显示默认消息。但我想(例如)单击“更改”类的链接并更新早期创建的实例的“消息”属性。但有些事情是错误的。我在 HTML 页面上的 jquery 代码:
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.show').clickAlert();
$('.change').click(function(){
$('.show').clickAlert('option', 'message', 'Updated message');
});
});
</script>
1) 如何在这个 jquery 插件中正确实现 option/update 方法?
2)我还有一个问题,但与主要问题无关。例如,我将使用这种模式创建插件。除了 init 和 option 方法之外,插件还有另外 10 个方法(例如)负责动画。在我的 init 方法中,我需要检查(使用 SWITCH 语句)我应该调用哪个动画方法并调用它。因为我需要多次执行此操作,所以最好创建一个函数以避免代码重复。创建这样的功能的最佳位置在哪里?我应该将其创建为一个新方法(如 init、option 和其他动画方法),还是可以简单地在 init 的“return this.each()”函数中创建它并在那里调用它几次?
最佳答案
这是一个范围问题,您需要更改选项的范围 - 通常您不会,但在本例中您需要更改,因此您更改为修改 $.extend(
,并给它一个引用:
;(function ($) {
var self = this;
self.defaults = {
message: 'This is default message'
};
self.options = {};
var methods = {
init: function (options) {
options = $.extend(self.options, self.defaults, options);
return this.each(function () {
$(this).click(function () {
alert(options.message);
});
});
},
option: function (key, myvalue) {
if (myvalue) {
self.options[key] = myvalue;
} else {
return self.options[key];
}
}
};
$.fn.clickAlert = function (method) {
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);
jQuery(document).ready(function ($) {
$('.show').clickAlert();
$('.change').click(function () {
$('.show').clickAlert('option', 'message', 'Updated message');
});
});
关于jquery - 如何在jquery插件中正确实现option/update方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14800095/