使用jquery实现全选反选效果

本文介绍如何利用jQuery实现表格中全选和反选的效果。通过绑定点击事件到全选按钮,更新所有复选框的状态,达到一键全选或全不选的功能。同时,当表格中任意复选框状态改变时,也会同步更新全选按钮的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src =" https://code.jquery.com/jquery-3.6.0.min.js "></script>
</head>
<body>
<button>全选</button>
<button>全不选</button>
<button>反选</button>
<br>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</body>
<script>
$('button').first().click(() => $(':checkbox').prop('checked', true))
$('button').first().next().click(() => $(':checkbox').prop('checked', false))
$('button').last().click(() => {
    // 获取属性的时候,没有隐式迭代了,只能获取到第一个
    // console.log($(':checkbox').prop('checked'));
    // $(':checkbox').prop('checked',    !$(':checkbox').prop('checked')      ) // 错误写法

    // jquery提供了一个方法,专门用于遍历jquery获取到的伪数组的
    // 伪数组.each(function(index, value){})
    $(':checkbox').each((i, v) => {
        // console.log(i, '----------------', v);
        
        // console.log(i, '---', $(v).prop('checked') )
        // $(v).prop('checked', !$(v).prop('checked'))
        v.checked = !v.checked
    })
})
</script>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值