2010-01-18 69 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