我正在创建一个jQuery插件,并且我需要让它响应窗口大小调整事件。我遇到的问题是,如果你只有一个插件实例,但是如果只有更多的实例只有后者可以工作,它才能正常工作。我的插件代码看起来像如何将窗口大小调整事件绑定到插件实例
(function ($) {
//Define it
var MyPlugin = function (element, options) {
//...
};
MyPlugin.prototype.init = function() {
$that = this;
$(window).bind('resize',function(e) {
//This only seems to get called for the last instance of the plugin
$that.recalculate();
});
}
MyPlugin.prototype.recalculate = function() {
}
$.fn.myPlugin = function (option) {
return this.each(function() {
var $this = $(this);
var options = typeof(option) === 'object' ? option : {};
new MyPlugin(this, options));
});
};
}(jQuery));
的问题是,窗口大小调整事件不会调用该插件的每个实例,所以如果我有两个实例,像这样,只有div2
会工作。
$('.div1').myPlugin();
$('.div2').myPlugin();
,又是什么大小调整处理呢? (你假设只有最后一个处理程序被调用几乎肯定是错的) – Amit
@Amit我更新了代码以使它更清晰 – Pattle