<li> 切換內部 checkbox 選中狀態(單選/多選均可)。<li> 單選,取消同組其他 radio,選中當前。<ul class="list-group" id="choice1">
<li><input type="checkbox" name="g" value="1"> A.1</li>
<li><input type="checkbox" name="g" value="2"> B.2</li>
</ul>
<ul class="list-group" id="choice2">
<li><input type="radio" name="g" value="1"> A.1</li>
<li><input type="radio" name="g" value="2"> B.2</li>
</ul>
<script>
$('.list-group').on('click', 'li', function(e) {
var $input = $(this).find('input');
// 若點擊的是 input 本身,瀏覽器已處理原生行為,直接返回
if (e.target === $input[0]) return;
if ($input.attr('type') === 'checkbox') {
$input.prop('checked', !$input.prop('checked'));
} else if ($input.attr('type') === 'radio') {
$input.prop('checked', true); // 同 name radio 自動互斥
}
$input.trigger('change'); // 觸發 change 事件供其他監聽器
});
</script>
<ul> 上,動態新增 <li> 亦生效。if (e.target === $input[0]) return; 防止點擊 input 時邏輯執行兩次(原生 + 代理)。checked 屬性必須用 .prop(),非 .attr()。name 的 radio 原生單選,僅需設定當前為 true。原回答嘗試手動遍歷取消其他 radio,且使用 .attr('checked','checked') 導致視覺未更新(瀏覽器 bug)。正確做法是信任原生單選機制,僅觸發 .prop('checked', true)。