我正在創建一個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