jQuery。如何取消选中所有复选框(已选中) [英] jQuery. How to uncheck all checkboxes except one (which was checked)

查看:653
本文介绍了jQuery。如何取消选中所有复选框(已选中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有html项目,例如:

I have html items, 4 example:

<div>
    <div><input type="checkbox" class="foo"> Checkbox</div>
    <div><input type="checkbox" class="foo"> Checkbox</div>
    <div><input type="checkbox" class="foo"> Checkbox</div>
    <div><input type="checkbox" class="foo"> Checkbox</div>
    <div><input type="checkbox" class="foo"> Checkbox</div>
    <div><input type="checkbox" class="foo"> Checkbox</div>
</div>

现在,我想要下一个:如果我点击任何复选框 - 复选框应该选中,其他复选框应取消选中。

And now, I want next: If I click on any checkbox - the checkbox should be checked and other checkboxes should be unchecked. How can I do it?

推荐答案

您可以使用收音机按钮按名称属性分组。如果您必须使用复选框执行此操作,那么您可以这样做:

You can use radio button and group them by name attributes. If you have to do it with checkboxes then you can do it this way,

现场演示

Live Demo

$('.foo').click(function(){     
      $('.foo').attr('checked', false);
      $(this).attr('checked', true);          
});

对于动态生成的html,您需要 on ,允许您使用静态父代理事件,您可以使用document与您不知道静态父代。

For dynamically generated html you need on that allows you to delegate the event with static parent, you can use document with you do not know static parent.

$(document).on('click','.foo', function(){     
      $('.foo').attr('checked', false);
      $(this).attr('checked', true);          
});

如果已知,文档可以由静态父代替。例如如果div包含动态生成的id parentdiv ,那么你可以有

Document could be replaced by static parent if it is known. e.g. if div contain dynamically generated has id parentdiv then you can have

`$('#parentdiv').on('click','.foo', function(){`

这篇关于jQuery。如何取消选中所有复选框(已选中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆