关于checkbox在前端页面中判断勾选方案

本文探讨了在前端开发中处理Checkbox勾选状态的两种方法:原生JavaScript解决方案和jQuery实现。通过这两种方式,可以有效地检查和管理Checkbox的状态,以实现更灵活的交互控制。

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

原生js方案

  let a=document.querySelector('input[type="checkbox"]')
    console.log(a.getAttribute('checked')); //null

    a.onclick=function(){
      if(a.getAttribute('checked')==null||a.getAttribute('checked')=='false'){
        a.setAttribute('checked','true')
      }else{
        a.setAttribute('checked','false')
      }
      b=document.getElementById('check').getAttribute('checked')
      console.log(b); //勾选时为true,不勾选时为false
      console.log(typeof b);  //string
      console.log(a);  //可以看到checked属性为true/false
    }

jquery方案

<script src="jquery-3.4.0.min.js"></script>
<script>
  $('input[type="checkbox"]').click(function(){
    if($('input[type="checkbox"]').is(':checked')){
      console.log('checked'); //页面里可以看到点击勾选时打印
    }else{
      console.log('empty'); //页面里可以看到点击非勾选时打印
    }
  })
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值