我在寻求帮助。我在这里用我的代码几乎清理了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 plugin multiple instantiation
但我就是不能让它工作。
当你在链接的jsfiddle点击el1链接时,我需要显示一个随机数和第一个插件实例的属性。当你在链接的jsfiddle点击el2链接时,我需要显示第二个随机数和第二个插件实例的属性。目前,这两个链接是相同的。
我的问题是如何为我的插件的每个实例创建自己的选项?然后,创建我自己的每个实例变量的正确方法是什么?谢谢!
发布于 2013-07-20 01:21:36
文本自身=这;aEl = $('',{ href:'#',
:this.options.propertyName,点击:函数(E){self._clicked();} });
在这里,您将赋值给一个全局变量self,它将被第二个插件实例化所覆盖,并且仅引用该变量。
添加var keyword以使其成为局部变量。
发布于 2013-07-20 01:41:51
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);
}
};小提琴:http://jsfiddle.net/hieuh25/XXw5h/8/
https://stackoverflow.com/questions/17751602
复制相似问题