1.概述
在项目中经常遇到列表中对复选框进行勾选操作,全选。。。反选。。
2. example
<html> <body> <form id="test-form" action="test"> <legend>请选择想要学习的编程语言:</legend> <fieldset> <p><label class="selectAll"><input type="checkbox"> <span class="selectAll">全选</span><span class="deselectAll">全不选</span></label> <a href="#0" class="invertSelect">反选</a></p> <p><label><input type="checkbox" name="lang" value="javascript"> JavaScript</label></p> <p><label><input type="checkbox" name="lang" value="python"> Python</label></p> <p><label><input type="checkbox" name="lang" value="ruby"> Ruby</label></p> <p><label><input type="checkbox" name="lang" value="haskell"> Haskell</label></p> <p><label><input type="checkbox" name="lang" value="scheme"> Scheme</label></p> <p><button type="submit">Submit</button></p> </fieldset> </form> <script src="jquery-3.1.0.js"></script> <script type="text/javascript"> $(function(){ (function(){ var form = $('#test-form'), langs = form.find('[name=lang]'), selectAll = form.find('label.selectAll :checkbox'), selectAllLabel = form.find('label.selectAll span.selectAll'), deselectAllLabel = form.find('label.selectAll span.deselectAll'), invertSelect = form.find('a.invertSelect'); // 重置初始化状态: form.find('*').show().off(); form.find(':checkbox').prop('checked', false).off(); deselectAllLabel.hide(); // 拦截form提交事件: form.off().submit(function (e) { e.preventDefault(); alert(form.serialize()); }); var count = 1; //点击全选/全不选框次数 selectAll.click(function(){ if(count++ %2){ selectAllLabel.hide(); deselectAllLabel.show(); $(this).prop("checked", false); langs.prop("checked", true); }else { selectAllLabel.show(); deselectAllLabel.hide(); $(this).prop("checked", false); langs.prop("checked", false); } }); invertSelect.on('click', function(){ langs.map(function(){ $(this).prop('checked', !this.checked); }); }); })(); }); </script> </body> </html>
Atas ialah kandungan terperinci jQuery中实现全选,反选实例代码 (推荐). Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!