这是一个把radio修饰后的按钮组,实现按下一个按钮,颜色变深,再按另一个按钮,之前变深的按钮恢复,此刻被按的按钮变深色。
绑定事件中的alert(value);会提示2次?请问是怎么回事?
CSS部分可忽略,直接看最后jquery。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>toggle radio</title>
<script src="http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
<style>
body {
font-family:sans-serif;
}
.toggle {
margin:4px;
background-color:#EFEFEF;
border-radius:4px;
border:1px solid #D0D0D0;
overflow:auto;
float:left;
}
.toggle label {
/*float:left;*/
width:4.0em;
}
.toggle label span {
text-align:center;
padding:3px;
display:block;
cursor: pointer;
}
.toggle label input {
position:absolute;
top:-20px;
}
.toggle .input-checked /*, .bounds input:checked + span works for firefox and ie9 but breaks js for ie8(ONLY) */ {
background-color:#404040;
color:#F7F7F7;
}
.toggle input:checked + span {
background-color:#404040;
color:#F7F7F7;
}
</style>
</head>
<body>
<div class="toggle">
<label><input type="radio" name="toggle" value="s01e01"><span>s01e01</span></label>
</div>
<div class="toggle">
<label><input type="radio" name="toggle" value="s01e02"><span>s01e02</span></label>
</div>
<div class="toggle">
<label><input type="radio" name="toggle" value="s01e03"><span>s01e03</span></label>
</div>
</body>
</html>
<script>
$('label').click(function(){
$(this).children('span').addClass('input-checked');
var value = $(this).children('input').val();
$(this).parent('.toggle').siblings('.toggle').children('label').children('span').removeClass('input-checked');
alert(value);
});
</script>
这个原因很有意思,我开始以为是事件冒泡。但是想想不对。然后代码改为:
event.target.type
主要是这个会触发两个一个是undefined
一个是radio
。因为label关联的radio也被有一个关联操作。当label被点击时,默认radio也被点击了一次。解决方法你可以
其实也可以这样写,因为你本身就是要控制
span
,所以直接绑定到span
上。然后DOM结构不需要改。