2010-01-18 66 views
0

請看看下面的例子:需要一些幫助編寫自定義jQuery插件

jQuery.fn.jqPos = function(target, settings) { 
    settings = jQuery.extend({ 
     offset: [ 0, 0 ] 
    }, settings); 

    return this.each(function() { 
     magic($(this), target, settings); 
     $(window).resize(function(){ 
      magic($(this), target, settings); 
     }); 
    }); 

    function magic(self, target, settings) { 
     // Here I position self close to target 
    } 
}; 

這工作完全當我第一次初始化插件,像$('div#one').jqPos($('div#two'));和魔術方法運行,因爲它應該。但在事件window.resize什麼都沒有發生(我希望它運行相同的設置和參數相同的方法)!

怎麼回事?如何克服?

編輯:在魔法(在window.resize),參數都是undefined

回答

1

你很困惑什麼this在你的$(window).resize(function(){ magic($(this), target, settings); }); this中指的不再是指你的元素,而是指window本身。嘗試:

return this.each(function() { 
     var $this = $(this); 
     magic($this, target, settings); 
     $(window).resize(function(){ 
      magic($this, target, settings); 
     }); 
    }); 
+0

哈哈當然。談論brainfart。感謝m8! – Mickel 2010-01-18 20:59:22