代码之家  ›  专栏  ›  技术社区  ›  Mickel

需要一些帮助来编写自定义jquery插件

  •  0
  • Mickel  · 技术社区  · 15 年前

    请看以下内容:

    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 什么都没有发生(我希望它以相同的设置和参数运行相同的方法)!

    怎么会?如何克服?

    编辑: 在magic方法(window.resize)中,参数都是 undefined .

    1 回复  |  直到 15 年前
        1
  •  1
  •   prodigitalson    15 年前

    你搞不懂什么 this 在你的 $(window).resize(function(){ magic($(this), target, settings); }); 不再指你的元素,而是指 window 本身。尝试:

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