想要的效果是点击radio所在的父元素时,父元素背景改变,且radio被选中。
HTML代码:
<ul class="linelist">
<li>
<input type="radio" name="gender" value="一" >
一</li>
<li>
<input type="radio" name="gender" value="二">
二</li>
<li>
<input type="radio" name="gender" value="三">
三</li>
</ul>
开始时的jQuery代码:
<script>
$(function() {
$(".linelist li").click(function(){
$(this).parent().children().removeAttr('checked');
$(this).parent().children().css('background-color','#fff');
$(this).css('background-color','#bff');
$(this).children('input').attr('checked','true');
});
});
</script>
这段代码在每一个radio被选中时,可以实现想要的效果,在radio的二次点击时,背景色可以变化,但是radio状态不变。
当天一直没有解决这个问题,后来查阅网上的资料,发现这里的attr应该改为prop,使用prop就可以实现多次点击。
<script>
$(function() {
$(".linelist li").click(function(){
$(this).parent().children().prop('checked','false');
$(this).parent().children().css('background-color','#fff');
$(this).css('background-color','#bff');
$(this).children('input').prop('checked','true');
});
});
</script>