javascript - 使用不同的参数将相同的函数绑定(bind)到窗口调整大小事件

标签 javascript jquery resize bind

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

(function($){
    $.fn.flexHeight = function(options) {

        if (!options){options = {};}
        var settings = $.extend({
            boxes: false
        }, options);

        function main(flexParent) {
            var $flexParent = flexParent;
            if (settings.boxes) {
                $children = $flexParent.find(settings.boxes);
            } else {
                $children = $flexParent.children
            }
            var maxHeight = 0;

            $children.each(function() {
                $(this).height('auto');
            });

            $children.each(function() {
                maxHeight = maxHeight > $(this).outerHeight(false) ? maxHeight : $(this).outerHeight(false);
            });

            $children.each(function() {
                $(this).height(maxHeight);
            });
        }

        return this.each(function() {
            $flexParent = $(this);
            main($flexParent);
            $(window).resize(function() {
                main($flexParent);
            });
        });
    }   
}(jQuery));

最佳答案

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

将代码更改为:

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

这使得 $flexParent 对于传递给每个元素的函数来说是本地的,因此每个元素都有一个变量。

关于javascript - 使用不同的参数将相同的函数绑定(bind)到窗口调整大小事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19452262/

相关文章:

javascript - 如果需要,Javascript 如何将网站用户重定向回登录页面?

javascript - 如何在 React 中调试一个简单的 API

javascript - 使用 Bootstrap 的 Typeahead displayKey 函数返回值

javascript - 如何将此curl 转换为jQuery AJAX POST?

html - 如何在移动设备上调整灵活文本区域的大小?

javascript - 将 Laravel 路由参数传递给 JavaScript

javascript - Uncaught ReferenceError : stripeResponseHandler is not defined

jquery - 如何构建底部为直线的平铺图片库?

javascript - 在同一空间添加和调整 DIV 的大小

c# - 如何从表单中删除调整大小指示器(右下角的灰线)?