做聊天的时候弄好友列表,选择好友的时候需要对checkbox进行选中处理。
这个时候,需要把其他checkbox取消掉,怎么取消?
一、代码实现
网上有很多直接给checkbox上函数,每个check都要加,这样很不靠谱。
我们第一想到的就是需要全局变量:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$(function(){ $(':checkbox').each(function(){ $(this).click(function(){ if($(this).attr('checked')) { $(':checkbox').removeAttr('checked'); } else{ $(':checkbox').not(this).removeAttr('checked'); $(this).attr('checked','checked'); } }); }); }); |
使用实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <script src="jquery-2.1.4.min.js"></script> </head> <body> <input type="checkbox" class="c1">c1<br> <input type="checkbox" class="c2">c2 <script> $(function(){ $(":checkbox").each(function(){ $(this).click(function(){ if($(this).attr("checked")){ $(":checkbox").removeAttr("checked"); }else{ $(":checkbox").not(this).removeAttr("checked"); $(this).attr("checked","checked"); } }) }) }) </script> </body> </html> |
二、总结
用完了这个东西之后,我发现有什么不对…
这个效果直接用radio不就实现了吗…为什么要这样大费周章呢…
像评论所说的一样,只要使用radio,同时变换一下radio的样式就好。
if else,其实jQuery有个.siblings()方法
看到最后你说直接用radio…你是不是想要checkbox的样式
这应该要找一下表单美化(radio/checkbox/select)的资料了。
谢谢你的回复,.siblings()挺好用的,谢谢指教。