【问题标题】:Binding same function to window resize event with different arguments将相同的函数绑定到具有不同参数的窗口调整大小事件
【发布时间】:2013-10-27 10:49:04
【问题描述】:

我正在制作一个简单的 JS 插件来垂直调整对象的大小。它工作正常,直到调整大小事件 - 其中$flexParent 似乎被设置为所有绑定的初始.each() 函数中的最后一个$flexParent。因此,对于传递给插件的三个“flexParent”,只有最后一个在调整大小事件上起作用;仅 3 次。显然我误解了这里的绑定,但我会很感激一些澄清!

(函数($){ $.fn.flexHeight = 功能(选项){ if (!options){options = {};} var 设置 = $.extend({ 框:假 }, 选项); 功能主(flexParent){ var $flexParent = flexParent; 如果(settings.boxes){ $children = $flexParent.find(settings.boxes); } 别的 { $children = $flexParent.children } 变量最大高度 = 0; $children.each(函数() { $(this).height('auto'); }); $children.each(函数() { maxHeight = maxHeight > $(this).outerHeight(false) ? maxHeight : $(this).outerHeight(false); }); $children.each(函数() { $(this).height(maxHeight); }); } 返回 this.each(function() { $flexParent = $(this); 主要($flexParent); $(窗口).resize(函数() { 主要($flexParent); }); }); } }(jQuery));

【问题讨论】:

    标签: javascript jquery resize bind


    【解决方案1】:

    $flexParent 被声明为全局变量,因此它在函数调用之间共享。当窗口调整大小回调被调用时,全局 $flexParent 变量将指向最后一个元素。

    将您的代码更改为:

      return this.each(function() {
            var $flexParent = $(this); // <-- added var here
            main($flexParent);
            $(window).resize(function() {
                main($flexParent);
            });
        });
    

    这使得$flexParent 成为传递给每个函数的局部变量,因此每个元素都有一个变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多