我正在制作一个简单的 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/