首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

jQuery 實現點擊 li 選中/取消 checkbox 與 radio 邏輯

     編輯:程式設計綜合問答

需求場景

  • Checkbox 組:點擊 <li> 切換內部 checkbox 選中狀態(單選/多選均可)。
  • Radio 組:點擊 <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>

關鍵點解析

  1. 事件代理:綁定在 <ul> 上,動態新增 <li> 亦生效。
  2. 避免雙重觸發:if (e.target === $input[0]) return; 防止點擊 input 時邏輯執行兩次(原生 + 代理)。
  3. 使用 .prop():操作 checked 屬性必須用 .prop(),非 .attr()。
  4. Radio 自動互斥:同 name 的 radio 原生單選,僅需設定當前為 true。

避坑指南

原回答嘗試手動遍歷取消其他 radio,且使用 .attr('checked','checked') 導致視覺未更新(瀏覽器 bug)。正確做法是信任原生單選機制,僅觸發 .prop('checked', true)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved