点击<li>元素自动勾选/取消复选框的实现异常问题
问题:点击选项li元素时切换内部复选框选中状态
需求目标
点击每个选项对应的<li>元素时,自动选中或取消其内部的input复选框。
现有页面代码
<h3 aria-label="Questions">Questions:</h3> <form method="POST" action="/submit"> <ul class="list-group mt-3"> <li class="list-group-item question-item"> <p class="question-text">What are the primary colors?</p> <div class="question" id="3"> <input type="hidden" name="first_modified_3" id="first_modified_3" value=""> <input type="hidden" name="last_modified_3" id="last_modified_3" value=""> <ul class="answer-list"> <li class="list-group-item"> <input type="checkbox" class="form-check-input" name="What are the primary colors?" value="Red" id="Red"> <span>Red</span> </li> <li class="list-group-item"> <input type="checkbox" class="form-check-input" name="What are the primary colors?" value="Green" id="Green"> <span>Green</span> </li> <li class="list-group-item"> <input type="checkbox" class="form-check-input" name="What are the primary colors?" value="Blue" id="Blue"> <span>Blue</span> </li> <li class="list-group-item"> <input type="checkbox" class="form-check-input" name="What are the primary colors?" value="Yellow" id="Yellow"> <span>Yellow</span> </li> </ul> </div> </li> </ul> </form>
(注:修正了原代码中错误的</input>闭合标签,<input>为自闭合标签,无需额外闭合)
已尝试方案及问题
在</body>前插入以下jQuery脚本后,点击<li>时所有选项的复选框都会被选中:
$(".list-group-item").click(function (e) { if (e.target.type !== 'checkbox') { var checkbox = $(this).find("input[type='checkbox']"); checkbox.prop("checked", !checkbox.prop("checked")).change(); } });
解决方案
问题原因
原选择器.list-group-item匹配了页面上所有带有该类的<li>,包括包裹整个问题的外层<li class="list-group-item question-item">。点击这个外层li时,find会获取所有子复选框,导致全部状态切换。
修正后的代码
将选择器缩小到仅匹配选项列表下的li元素,避免影响外层容器:
// 仅绑定选项列表内的li元素 $(".answer-list .list-group-item").click(function(e) { // 排除点击复选框本身的情况 if (!$(e.target).is('input[type="checkbox"]')) { const checkbox = $(this).find('input[type="checkbox"]'); checkbox.prop('checked', !checkbox.prop('checked')).change(); } });
如果页面是动态生成的选项,建议使用事件委托,确保新添加的元素也能触发事件:
$(document).on('click', '.answer-list .list-group-item', function(e) { if (!$(e.target).is('input[type="checkbox"]')) { const checkbox = $(this).find('input[type="checkbox"]'); checkbox.prop('checked', !checkbox.prop('checked')).change(); } });
内容的提问来源于stack exchange,提问作者Nicolaesse
相关产品推荐
相关产品推荐

