我在寻求帮助。我的代码在这里几乎是干净的jquery样板:
http://jsfiddle.net/XXw5h/7/
;(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 = {
someVal: Math.round(Math.random() * 99999999),
init: function() {
self = this;
aEl = $('<a/>', {
href: '#',
text: this.options.propertyName,
click: function(e){self._clicked();}
});
$(".el1").before(aEl);
$(".el1").before("<br/>");
},
_clicked: function(el, options) {
alert("Random value of el instance:" + this.someVal);
alert("Property name:" + this.options.propertyName);
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin( this, options ));
}
});
};
})( jQuery, window, document );
$('.el1').defaultPluginName({
propertyName: 'el1 link '
});
$('.el2').defaultPluginName({
propertyName: 'el2 link'
});
我的问题是我需要多个实例化,这就是我的麻烦开始的地方。我知道我的问题在这里得到了回答:
jQuery插件多实例化
但我就是做不到。
当你点击链接jsfiddle的el1链接时,我需要显示一个随机数和插件第一个实例的属性。当你点击链接jsfiddle的el2链接时,我需要显示第二个随机数和插件第二个实例的属性。目前这两个链接都是一样的。
我的问题是如何为我的插件的每个实例创建自己的选项?然后,创建自己的每个实例变量的正确方法是什么?谢谢
self = this; aEl = $('<a/>', { href: '#', text: this.options.propertyName, click: function(e){self._clicked();} });
您在这里为全局变量self
赋值,它将被第二个插件实例化覆盖,并且只引用它。
添加var
关键字使其成为局部变量。
Bergi的答案是真的,您应该将self
定义为局部变量。此外,我想补充一点,你应该让someVal
成为一个函数,每次点击链接时都有随机数,否则在初始化时它们将是相同的数字。所以更新后的代码应该是:
Plugin.prototype = {
someVal: function () {
return Math.round(Math.random() * 99999999)
},
init: function() {
var self = this;
aEl = $('<a/>', {
href: '#',
text: self.options.propertyName,
click: function (e) {
e.preventDefault();
self._clicked();
}
});
$(".el1").before(aEl);
$(".el1").before("<br/><br/>");
},
_clicked: function(el, options) {
alert("Random value of el instance:" + this.someVal());
alert("Property name:" + this.options.propertyName);
}
};
Fiddle:http://jsfiddle.net/hieuh25/XXw5h/8/