如何让jQuery代码作用于多个同名class的TwoColumnUnit元素?
问题原因
你的代码只对第一个.TwoColumnUnit生效,是因为document.querySelector会返回整个文档中第一个匹配选择器的元素。在.each循环的每一次迭代中,你都在操作同一个(第一个).TwoColumnUnit_Left和.TwoColumnUnit_Right,而不是当前循环对应的.TwoColumnUnit内部的元素。
修复方案
需要将元素查询的范围限定在当前循环的.TwoColumnUnit内部,而不是整个文档。以下是两种修复后的代码:
方案1:使用jQuery语法(更简洁一致)
$('.TwoColumnUnit').each(function() { const $currentUnit = $(this); // 仅在当前单元内查找左右列 const $leftCol = $currentUnit.find('.TwoColumnUnit_Left'); const $rightCol = $currentUnit.find('.TwoColumnUnit_Right'); [$leftCol, $rightCol].forEach(function($col) { if ($col.length) { const $boxes = $col.find('.col-sm-12.col-md-6'); let maxHeight = 0; // 重置高度并计算最大高度 $boxes.each(function() { $(this).css('height', ''); maxHeight = Math.max(maxHeight, $(this).outerHeight()); }); // 统一设置高度 $boxes.css('height', maxHeight + 'px'); } }); });
方案2:保留原生JS语法(修复作用域)
$('.TwoColumnUnit').each(function() { const currentUnit = this; // 在当前单元内查询左右列,而非整个文档 const leftCol = currentUnit.querySelector('.TwoColumnUnit_Left'); const rightCol = currentUnit.querySelector('.TwoColumnUnit_Right'); [leftCol, rightCol].forEach(function(col) { if (col) { const boxes = col.getElementsByClassName('col-sm-12 col-md-6'); let maxHeight = 0; Array.from(boxes).forEach(function(box) { box.style.height = ''; maxHeight = Math.max(maxHeight, box.offsetHeight); }); Array.from(boxes).forEach(function(box) { box.style.height = maxHeight + 'px'; }); } }); });
关键改动说明
- 使用
$(this)(jQuery)或this(原生JS)指代当前循环的.TwoColumnUnit元素 - 通过
find()(jQuery)或currentUnit.querySelector()(原生JS)在当前元素的子树内查找目标元素,确保每次循环处理的是对应单元内的内容
内容的提问来源于stack exchange,提问作者user22708374
相关产品推荐
相关产品推荐

