HTML代码
<fieldset>
<legend>喜爱角色选择</legend>
<input type="checkbox" name="role1" id="role11" value="卡卡罗特" data-name="赛亚人"><label for="role1">卡卡罗特</label>
<input type="checkbox" name="role1" id="role12" value="孙悟天" data-name="赛亚人"><label for="role2">孙悟天</label>
<input type="checkbox" name="role1" id="role13" value="18号" data-name="人造人"><label for="role3">18号</label>
</fieldset>
jQuery使用场景
用例1:获取选中的值
// 复选框可能会返回多个结果,使用each()遍历返回结果
$('input[name="role1"]:checked').each(function(){
// this是dom对象,可以用$(this)转为jQuery对象
console.log($(this).val());
});
用例2:获取改变的值
$('input[name="role1"]').on("change",function(){
console.log("check的value值:" + $(this).val());
// 做其他处理
})
用例3:选中禁用
$('input[name="role1"]').on("change",function(){
if($(this).is(":checked")){
$(this).attr("disabled","disabled");
// 做其他处理
}
})
用例4:取消禁用和选中
$('input[name="role1"]').removeAttr("disabled"); //移除禁用
$('input[name="role1"]').prop("checked",false); //移除选中
用例5:模拟操作选中和取消选中
$('input[name="role1"]').on("change",function(){
let that = this;
if($(this).is(":checked")){
console.log("选中:" + $(that).val());
// 是选中,做业务处理
} else{
console.log("取消选中:" + $(that).val());
// 取消选中,做业务处理
}
})
用例6:获取选中值的属性值
$('input[name="role1"]').on("change",function(){
console.log("checkbox的data-name属性值:" + $(this).attr("data-name"));
// 做其他处理
})