虽然其他的反应是正确的,我会喜欢添加一些东西:如果HTML页面中有其他复选框,只需通过类型(复选框)选中复选框,就可以选中与你想要的无关的其他复选框。
最少添加的代码应该不会影响其他代码部分,那就是为复选框指定一个特定的类。例如,如果您的复选框代表的爱好,你加他们hobby_checkbox类:
<div>
<input type='checkbox' name='select_all' /> Select all hobbies
<br>
<input type='checkbox' class='hobby_checkbox' name='check1' /> Ski
<br>
<input type='checkbox' class='hobby_checkbox' name='check2' /> Travel
<br>
<input type='checkbox' class='hobby_checkbox' name='check3' /> PC Games
<br>
<br>
<input type='checkbox' class='other_checkbox' name='other_check' /> Subscribe
</div>
然后,当你要选择你要检查的复选框,选择只属于该类的那些你想要的:
$(document).on('change', '[name="select_all"]', function(){
var $this = $(this);
var div = $this.parent();
var ischecked = $this.prop('checked');
div.find(':checkbox.hobby_checkbox').prop('checked', ischecked);
});
这样可以避免检查不相关的订阅复选框。
你可以在行动here看到它。
变化inpuy输入 – 2012-07-19 14:40:40