可能重复:
您将如何更改这种代码?
我如何通过 jQuery 将这些变量传递给选项,这样当用户使用插件时,他们必须从 HTML 初始化插件,如下所示:
<script>
$('.elem').pluginName({
theme: 'blue',
animSpeed: 200
});
</script>
这是我的 jQuery 代码。很乱,但看看。如何将变量更改为选项?
$(function () {
var theme = "sunburst";
var btnColor = "yellow";
var icon = "power";
var message = "Hello World";
var animSpeed = 300;
var animType = 'fadeIn';
var btnText = "Purchase";
var btnLink = 'http://www.google.com';
var closeStyle = "dark";
var content =
'<div id="mn_close" class="' + closeStyle + '"></div>' +
'<div id="mn_border"></div>' +
'<i class="icon-' + icon + '"></i>' +
'<span class="mn_message">' + message + '</span>';
// '<a href="' + btnLink + '" class="button ' + btnColor + '">' + btnText + '</a>';
$("#mn_close").live("click", function () {
$('.mn_bar').animate({
height: '0'
}, animSpeed, function () {});
});
var mn_bar = $(".mn_bar");
mn_bar.append(content);
$(function () {
mn_bar.addClass("animated");
mn_bar.addClass(animType);
mn_bar.addClass(theme)
});
});
或者这里是jsfiddle。http://jsfiddle.net/LwGRV/6/
我也在尝试将代码实现到这种标准类型的 jQuery 代码中,但未能合并:
;(function ( $, window, document, undefined ) {
var pluginName = "defaultPluginName",
defaults = {
propertyName: "value"
};
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
},
yourOtherFunction: function(el, options) {
// some logic
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin( this, options ));
}
});
};
})( jQuery, window, document );
如果有人能对此有所了解,请提前非常感谢。