Question. 问题
在开发过程中,默认的单选框(radio)和复选框(check)样式比较难看,因此我们往往需要对其样式进行包装,一种方式就是在 input 外面包装一层 a 标签。
/* css部分 */
.survey {
display: block;
color: #888;
padding: 5px 15px;
background: #fff;
width: 200px;
margin:10px 30px 10px;
font-size: 14px;
position: relative;
border: 1px solid #ddd;
border-radius: 10px;
text-decoration: none;
}
/* html部分 */
<a href="javascript:void(0);" class="survey check-box">
<input name="subject" type="checkbox" style="display: none;">PHP
</a>
在移动端,甚至往往将 input 选择框也隐藏掉:
<a href="javascript:void(0);" class="survey check-box">
<input name="subject" type="checkbox" style="display: none;">PHP
</a>
而在实现上,则通过通过 JS 或者 Jquery 触发 a 标签来触发 input 选择的切换,比较方便的一种方式就是使用 Jquery。
$(".check-box").click(function(){
var input = $(this).children('input');
if (input.attr('checked')) {
input.attr('checked',false);
} else {
input.attr('checked',true);
}
});
但是,在部分浏览器(chrome谷歌浏览器)中,通过 attr() 方法,第一次点击能正常触发选中功能,而再次点击就会出现不能将选择框选中的问题。
Solution. 解决
通过 attr(‘checked’,true) 能实现将 checked 属性添加到 input 中:
但是,真正能让选择框切换的只有第一次:
第二次、第三次选中均不能生效。
一个很奇怪的问题,其中的作用机理我们不做深究,只讲解决方法,在遇到这个问题的时候改用 prop() 方法就能实现切换:
$(".check-box").click(function(){
var input = $(this).children('input');
if (input.prop('checked')) {
input.prop('checked',false);
} else {
input.prop('checked',true);
}
});
Extension. 扩展
以下是通过 bind() 绑定,实现切换单选框(radio)、复选框(check)的选择状态的代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<style type="text/css">
.survey {
display: block;
color: #888;
padding: 5px 15px;
background: #fff;
width: 200px;
margin:10px 30px 10px;
font-size: 14px;
position: relative;
border: 1px solid #ddd;
border-radius: 10px;
text-decoration: none;
}
</style>
</head>
<body>
<a href="javascript:void(0);" class="survey check-tap">
<input name="values_0" type="radio" value="A. 男">A. 男
</a>
<a href="javascript:void(0);" class="survey check-tap">
<input name="values_0" type="radio" value="B. 女">B. 女
</a>
<script type="text/javascript">
(function(){
$('.check-tap').bind('click',function(e){
var el = $(e.target);
var el_child = el.children('input');
var color = el.css('color');
if (el_child.prop("checked")) {
el_child.prop("checked",false);
el.css('color','#888');
el.css('background-color','#fff');
} else {
el_child.prop("checked",true);
el.css('color','red');
el.css('background-color','#eee');
if (el_child.attr('type')=='radio') {
el.siblings().css('color','#888');
el.siblings().css('background-color','#fff');
}
}
return false;
});
})();
</script>
</body>
</html>
本文介绍了在前端开发中遇到的一个问题,即使用JQuery的attr()方法在Chrome浏览器中无法正常切换单选框(radio)和复选框(check)的选中状态。通过分析,发现attr()方法在第二次点击时失效。解决方案是改用prop()方法,可以成功实现选择框的切换。同时提供了通过bind()绑定事件来切换选择状态的代码示例。
1632

被折叠的 条评论
为什么被折叠?



