jQuery 插件,最后一个初始化是什么时候触发的?
jQuery plugin, when the last init has fired?
给定以下 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 何时被解雇?那意味着最终实例何时被初始化?
如果你 运行 使用 jQuery 的 $.each() 方法遍历所有元素,你可以确定元素的最后一次初始化,就像这样:-
首先存储 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>
给定以下 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 何时被解雇?那意味着最终实例何时被初始化?
如果你 运行 使用 jQuery 的 $.each() 方法遍历所有元素,你可以确定元素的最后一次初始化,就像这样:-
首先存储 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>