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

jQuery点击按钮切换文本显隐时加减图标无法同步切换

问题根源

你的点击事件逻辑写死了单向状态:每次触发点击都会强制隐藏加号图标、显示减号图标,没有做状态双向切换,所以第一次点击能正常从加号切到减号,后续点击不管描述是显示还是隐藏,图标都会被固定在减号状态,自然切不回去。

直接修复代码

和你切换描述文本的逻辑一致,两个图标也用toggle()方法做同步切换即可,不需要手动写css()强制设置display属性:

$(document).ready(function() {
  $(".minus-icon").hide();
  $(".plus-button").click(function(){
    // 先定位到当前按钮所属的内容组容器,减少重复查询
    const $group = $(this).closest(".toggle-description");
    // 切换描述文本
    $group.find(".more-text").toggle();
    // 同步切换两个图标
    $group.find(".plus-icon").toggle();
    $group.find(".minus-icon").toggle();
  });
});
更优实现建议

当前用两个img标签来回切换显示的写法冗余度比较高,推荐用class切换+CSS背景图的方式实现,后续改图标、调整样式都更方便:

  1. 先把按钮里的两个img标签删掉,只保留按钮本身
  2. 写对应状态的CSS:
.plus-button {
  width: 20px;
  height: 20px;
  border: none;
  padding: 0;
  background: transparent no-repeat center / contain;
  cursor: pointer;
}
.plus-button.state-plus {
  background-image: url('https://cdn-icons-png.flaticon.com/512/748/748113.png');
}
.plus-button.state-minus {
  background-image: url('https://cdn-icons-png.flaticon.com/512/43/43625.png');
}
  1. 简化后的JS逻辑:
$(document).ready(function() {
  // 初始化按钮状态
  $(".plus-button").addClass('state-plus');
  $(".plus-button").click(function(){
    const $group = $(this).closest(".toggle-description");
    $group.find(".more-text").toggle();
    // 直接切换按钮的两个状态class即可
    $(this).toggleClass('state-plus state-minus');
  });
});

内容的提问来源于stack exchange,提问作者KasiaW

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 08:06:19