使用jQuery移除元素属性时if分支未触发,求问题原因排查
问题原因及修复方案
核心错误点
用
attr()获取CSS样式属性无效max-height是元素style属性内的CSS声明,并非DOM元素的独立属性。你用attr('max-height')会直接返回undefined,因为<article>本身没有名为max-height的属性,自然无法触发if分支。DOM元素调用
next()方法的写法错误
原生DOM元素没有next()方法,你写的$(this.next())属于语法错误,正确写法是先把this包装成jQuery对象,再调用next(),即$(this).next()。removeAttr("max-height")无法清除CSS样式removeAttr用于移除DOM元素的属性(比如id、class这类),但max-height是style属性里的子声明,调用removeAttr("max-height")不会产生任何效果。
修复后的代码
方案1:用jQuery的css()方法检查和清除样式
$(".accordion label").on("click", function(e){ const $target = $(this).next(); // 检查max-height是否为非默认值(默认是none) if($target.css('max-height') !== 'none'){ $target.css('max-height', ''); } });
方案2:直接检查DOM元素的style属性
$(".accordion label").on("click", function(e){ const $target = $(this).next(); // 检查style属性中是否存在maxHeight声明 if($target[0].style.maxHeight){ $target.css('max-height', ''); } });
内容的提问来源于stack exchange,提问作者Prithviraj Mitra
相关产品推荐
相关产品推荐

