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

如何实现勾选复选框时切换对应列表项的Active/Inactive状态

解决方案

核心逻辑实现

要实现勾选复选框时仅修改对应项的状态,关键是通过$(this)定位当前触发事件的复选框,再找到其所属的状态元素进行修改。在你的change事件回调中添加以下代码即可完成需求:

elem.find('.Check').change(function() {
  // 获取当前复选框的选中状态
  const isChecked = $(this).is(':checked');
  // 定位当前项对应的状态文本元素
  const statusElement = $(this).closest('.NameOfCountry').find('.InActive');
  
  if (isChecked) {
    statusElement.text('Active').css('color', 'green');
  } else {
    statusElement.text('Inactive').css('color', 'red');
  }
})

额外优化建议

  1. 修复重复ID问题:原代码每次循环都会生成一个id="CountryList"的ul,而页面中ID必须唯一。建议把ul容器的创建移到循环外,避免重复:
function createList() {
  const liTag = $('.Handler');
  // 先创建唯一的ul容器
  const ul = $('<ul id="CountryList"></ul>');
  
  for (let i = 0; i < Countries.length; i++) {
    const List = `
      <li>
        <div class="NameOfCountry">
          <input type="checkbox" class="Check">
          <p class="CountryName">Hello</p>
          <p class="InActive">Inactive</p>
        </div>
      </li>   
    `;
    
    var elem = $(List);
    elem.find('.CountryName').html(Countries[i]);
    // 绑定状态切换事件
    elem.find('.Check').change(function() {
      const isChecked = $(this).is(':checked');
      const statusElement = $(this).closest('.NameOfCountry').find('.InActive');
      
      if (isChecked) {
        statusElement.text('Active').css('color', 'green');
      } else {
        statusElement.text('Inactive').css('color', 'red');
      }
    })
    ul.append(elem);
  }
  // 最后将ul添加到页面
  liTag.append(ul);
}
  1. 样式与逻辑分离:如果不想在JS中直接操作样式,可以新增一个.Active类,通过切换类来维护样式,更符合前端开发规范:
.Active {
  background: white;
  border-radius: 5px;
  color: green;
  font-size: 11px;
  font-weight: bold;
  width: 30%;
  padding: 5px;
  text-align: center;
}

对应的JS代码修改为:

elem.find('.Check').change(function() {
  const isChecked = $(this).is(':checked');
  const statusElement = $(this).closest('.NameOfCountry').find('.InActive, .Active');
  
  if (isChecked) {
    statusElement.text('Active').removeClass('InActive').addClass('Active');
  } else {
    statusElement.text('Inactive').removeClass('Active').addClass('InActive');
  }
})

内容的提问来源于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 16:43:17