版权声明: https://blog.csdn.net/qq_41115965/article/details/83830950
jQuery操作复选框状态
在很多项目中,我们通常需要用户同意相关协议,才可以进行某种操作;在这种场景下,我们需要获取复选框的checked属性,才可以正确的执行判断。
代码结构
HTML文件
<div class="tips">
<input type="checkbox" />
<a href="privacyPolicy.html">我已阅读并同意《
<span>用户协议和隐私条款</span>》
</a>
</div>
CSS文件
.tips {
font-size: 28px;
margin-top: -30px !important;
margin-bottom: 30px;
line-height: 80px;
>input[type="checkbox"]{
width: 37px;
height: 37px;
vertical-align: middle;
border-radius: 50%;
margin-right: 10px;
margin-left: 10px;
cursor: pointer;
}
>a {
text-decoration: none;
color: #000000;
vertical-align: middle;
>span {
border-bottom: 3px solid #3196DA;
}
}
JS文件
// 复选框选中触发的事件
$(".tips input[type='checkbox']").click(function() {
if($(this).prop("checked")) {
$(this).prop("checked", true);
console.log("AAAA",$(this).prop("checked"));
console.log("选中了!!!!!");
} else {
$(this).prop("checked", false);
console.log("BBBB",$(this).prop("checked"));
console.log("对不起,没选中");
}
})
使用介绍
通过代码中的 $(this).prop(“checked”) ,我们可以获取对应的复选框的checked属性,其返回的结果是 true / false;在需要做判断的地方,我们利用布尔值 $(this).prop(“checked”) 即可。