给出以下jQuery插件代码:
;(function ( $, window, document, undefined ) {
var pluginName = 'myPluginName';
// Create the plugin constructor
function Plugin ( element, options ) {
this.element = element;
this._name = pluginName;
this._defaults = $.fn.myPluginName.defaults;
this.options = $.extend( {}, this._defaults, options );
this.init();
}
// Avoid Plugin.prototype conflicts
$.extend(Plugin.prototype, {
// Initialization logic
init: function () {
},
});
$.fn.myPluginName = function ( options ) {
this.each(function() {
if ( !$.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
});
return this;
};
$.fn.myPluginName.defaults = {
property: 'value',
onComplete: null
};
})( jQuery, window, document );
插件的每个实例都在init函数中。有没有办法知道最后一次init被解雇的时间?这意味着最终实例已经初始化了吗?
答案 0 :(得分:0)
如果使用jQuery的$ .each()meathod运行所有元素,则可以确定元素的最后一次启动,如下所示: -
首先存储length of the elements
- 1,然后检查迭代的当前元素是否具有与length of the elements
匹配的索引 - 1.如果是,则是最后一次初始化!
AddBg = ($elem) => {
$elem.css({
'background-color' : 'red'
})
}
let initElemLength = $('div').length - 1;
$('div').each(function(i , e) {
AddBg($(this));
if(i === initElemLength) { console.log('Last initilization Done!') }
});
div {
height: 10vh;
background: #ccc;
}
div:nth-of-type(even) {
background: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>