You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 04:52:15