如何实现勾选复选框时切换对应列表项的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'); } })
额外优化建议
- 修复重复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); }
- 样式与逻辑分离:如果不想在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
相关产品推荐
相关产品推荐

