原生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>