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

如何简化复选框状态切换及Active显示的冗余JavaScript代码?

优化复选框状态同步与列表渲染代码

需求:

  • 勾选复选框时,对应项的status值改为1;取消勾选时改为0
  • 根据status值显示/隐藏“Active”文本(status=1显示,0隐藏)
  • 当前代码在国家列表元素增加时会变得冗长,需要优化

优化后的完整代码

HTML

<div class="Handler"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

CSS

* {
  margin: 0;
  padding: 0;
  outline: none;
  box-sizing: border-box;
}

body {
  background: #40fff5;
}

.Handler {
  width: 100%;
  padding: 12px;
}

ul li {
  list-style: none;
}

.NameOfCountry {
  background: blue;
  width: 100%;
  display: flex;
  justify-content: space-between;
  gap: 6px;
  border-radius: 8px;
  align-items: center;
  padding: 8px;
  margin-top: 6px;
}

.CountryName {
  color: white;
  font-size: 18px;
  font-weight: bold;
  width: 100%;
  text-align: center;
}

.IfActive {
  background: white;
  border-radius: 5px;
  color: red;
  font-size: 11px;
  font-weight: bold;
  width: 30%;
  padding: 5px;
  text-align: center;
  display: none;
}

.status {
  background: red;
  color: white;
  font-size: 17px;
  font-weight: bold;
  width: 40px;
  text-align: center;
}

.hidden {
  display: none;
}

JavaScript

const Countries = ["Philippines", "New York", "Singapore"];

function createList() {
  const handler = $('.Handler');
  // 只创建一个ul,避免重复id(HTML规范中id必须唯一)
  const countryList = $('<ul id="CountryList"></ul>');
  
  Countries.forEach(country => {
    const listItem = $(`
      <li>
        <div class="NameOfCountry">
          <input type="checkbox" class="Check">
          <p class="CountryName">${country}</p>
          <p class="status">0</p>
          <p class="IfActive">Active</p>
        </div>
      </li>
    `);
    countryList.append(listItem);
  });
  
  handler.append(countryList);
}

createList();

// 事件委托:父元素统一处理子元素事件,新增列表项自动生效
$('.Handler').on('change', '.Check', function() {
  const isChecked = $(this).prop('checked');
  const parentContainer = $(this).closest('.NameOfCountry');
  
  // 更新当前项的status值
  parentContainer.find('.status').text(isChecked ? '1' : '0');
  // 同步显示/隐藏当前项的Active文本
  parentContainer.find('.IfActive').css('display', isChecked ? 'block' : 'none');
});

核心优化点

  • 修复DOM结构问题:原来循环生成多个重复id的ul,现在改为只创建一个ul容器,循环添加li项,符合HTML规范。
  • 事件委托简化绑定:无需给每个复选框单独绑定事件,通过父元素.Handler统一处理所有.Check的change事件,新增列表项时无需额外操作,适配任意长度的国家列表。
  • 移除冗余轮询逻辑:删掉了setInterval和隐藏按钮的无用逻辑,直接在复选框状态变化时同步更新对应元素,性能更优、逻辑更直接。
  • 动态适配任意列表长度:通过closest定位当前复选框所在的容器,直接操作对应项的状态元素,无论列表有多少项都能自动适配,不会因为元素增加导致代码冗长。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 08:25:08