jQuery each遍历问题:多div按内容设高度却始终取首个条件值
问题分析与修复方案
嘿,我一眼就瞅出问题所在了——你的条件判断犯了一个jQuery新手常踩的坑!
为啥所有元素都用了第一个高度?
你代码里的if ($(this).find('.box-site-tags'))写法有问题:jQuery的.find()方法不管有没有找到匹配元素,都会返回一个jQuery对象,而在JS里,对象属于“真值”,哪怕是空的jQuery对象也会被判定为true。这就导致第一个if条件永远成立,后面的else if和else完全没机会执行,所有.box-site-promo自然都被设成200px高度了。
正确的判断姿势
要检查是否找到元素,你得用jQuery对象的.length属性:
- 找到元素时,
.length会大于0(转为布尔值是true) - 没找到时,
.length等于0(转为布尔值是false)
修正后的代码
$('.box-site-promo').each(function(index) { console.log($(this)); let heightBox; // 把变量声明在循环内,避免全局污染 // 检查length属性来判断是否找到元素 if ($(this).find('.box-site-tags').length) { heightBox = 200; console.log(index + " " + heightBox); } else if ($(this).find('.box-site-authors').length) { heightBox = 100; console.log(index + " " + heightBox); } else { heightBox = 300; console.log(index + " " + heightBox); } $(this).height(heightBox); });
额外优化小技巧
如果想让代码更简洁,也可以用嵌套三元表达式(前提是逻辑不复杂,保证可读性):
$('.box-site-promo').each(function(index) { const hasTags = $(this).find('.box-site-tags').length; const hasAuthors = $(this).find('.box-site-authors').length; const heightBox = hasTags ? 200 : hasAuthors ? 100 : 300; console.log(index + " " + heightBox); $(this).height(heightBox); });
内容的提问来源于stack exchange,提问作者erdys
相关产品推荐
相关产品推荐

