检查传递的元素是否已经初始化,返回其实例javascript插件 [英] Check if passed element is already initialized return its instance javascript plugin
问题描述
插件代码:
( function() {
this.Modal = function modal( selector, options ) {
// If there's a passed element is already initialized return its instance
if ( !modal.instances ) {
modal.instances = {};
}
if ( modal.instances[ selector ] ) {
return modal.instances[ selector ];
}
modal.instances[ selector ] = this;
// Plugin options
var defaults = {
open: false
};
this.options = extendDefaults( defaults, options );
selector.style.setProperty( 'background-color', 'red' );
}
function extendDefaults( source, properties ) {
var property;
for ( property in properties ) {
if ( properties.hasOwnProperty( property ) ) {
source[ property ] = properties[ property ];
}
}
return source;
}
}() );
要运行插件:
$( window ).on( 'load', function() {
$( '.button' ).each( function() {
var myPlugin = new Modal( this );
} );
} );
HTML代码:
<button class="button">First Button</button>
<button class="button">Second Button</button>
<button class="button">Third Button</button>
代码上的错误,即第一个按钮仅会读取插件并获得红色背景,第二个和第三个按钮将返回第一个按钮的实例,而且我不知道为什么发生这种情况,按钮具有相同的功能类,是的,但是有不同的元素.
The wrong on the code that the first button only will read the plugin and gets the red background and the second and third buttons will return the instance of the first button, And I don't why this happens the buttons has the same class, yes but there are different elements.
我需要从插件调用的每个按钮都具有红色背景色,同时避免多次初始化(如果传递的元素已经初始化,则返回其实例).
I need every button called from the plugin gets the red background color and at the same time avoid initialized multiple times (If the passed element is already initialized return its instance).
推荐答案
好.问题在于这里的对象方法是因为对象的键只能是字符串.当我们试图像这样 modal.instances [选择器] = this;
时,我们实际上将拥有这个 modal.instances ['[object HTMLButtonElement]'] = this;