基于 jQuery 实现复选框全选与选中项查询功能

一、功能实现核心知识点
  • jQuery 选择器:通过$('selector')精准选取复选框元素
  • 属性操作:使用prop('checked', boolean)设置 / 获取复选框选中状态
  • 事件绑定:通过on('event', callback)监听用户操作
  • 集合遍历:利用each()方法遍历复选框集合
  • 数据过滤:通过:checked选择器筛选已选中的复选框
二、全选功能实现方案
1. 基础 HTML 结构

html

预览

<div class="checkbox-group">
  <input type="checkbox" id="select-all" class="check-all"> 全选
  <div class="checkbox-list">
    <input type="checkbox" class="item-checkbox" value="1"> 选项1<br>
    <input type="checkbox" class="item-checkbox" value="2"> 选项2<br>
    <input type="checkbox" class="item-checkbox" value="3"> 选项3<br>
    <input type="checkbox" class="item-checkbox" value="4"> 选项4<br>
  </div>
</div>
2. jQuery 全选代码实现

javascript

$(function() {
  // 全选/全不选功能
  $('#select-all').on('change', function() {
    const isChecked = $(this).prop('checked');
    // 批量设置所有子复选框的选中状态
    $('.item-checkbox').prop('checked', isChecked);
  });
  
  // 子复选框变化时更新全选框状态
  $('.item-checkbox').on('change', function() {
    const allCheckboxes = $('.item-checkbox');
    const checkedCount = allCheckboxes.filter(':checked').length;
    
    // 全选状态判断
    if (checkedCount === allCheckboxes.length) {
      $('#select-all').prop('checked', true);
    } else if (checkedCount > 0) {
      // 半选状态(需配合CSS样式)
      $('#select-all').prop('indeterminate', true);
    } else {
      $('#select-all').prop({
        checked: false,
        indeterminate: false
      });
    }
  });
});
3. 半选状态优化(CSS 实现)

css

.check-all:indeterminate {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12"><rect width="12" height="12" fill="none" stroke="currentColor" stroke-width="2"/></svg>');
  background-repeat: no-repeat;
  background-position: center;
  background-size: 10px;
}
三、选中项查询功能实现
1. 获取选中项值数组

javascript

function getSelectedValues() {
  // 使用:checked选择器过滤选中的复选框
  const selectedItems = $('.item-checkbox:checked');
  const values = [];
  
  // 遍历收集value值
  selectedItems.each(function() {
    values.push($(this).val());
  });
  
  return values;
}

// 示例调用
const selectedValues = getSelectedValues();
console.log('选中项值:', selectedValues);
2. 获取选中项文本内容

javascript

function getSelectedTexts() {
  const selectedItems = $('.item-checkbox:checked');
  const texts = [];
  
  selectedItems.each(function() {
    // 获取复选框后的文本内容(需根据实际HTML结构调整)
    const text = $(this).next('span, br').text().trim() || $(this).parent().text().trim();
    texts.push(text);
  });
  
  return texts;
}
3. 批量操作选中项(示例:禁用选中项)

javascript

function disableSelected() {
  $('.item-checkbox:checked').prop('disabled', true);
}
四、高级功
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值