jQuery 全选和反选demo
前段时间做了一个全选和反选的功能,最近不忙了,做了一个简化版的demo。
全部代码如下:
<!DOCTYPE html> <html> <head> <title>全选反选</title> <style type="text/css"> ul,li{ list-style: none; } .btn { margin-left: 40px; } </style> </head> <body> <ul id="music"></ul> <hr> <div class="btn"> <label id="all"> <input type="checkbox" name="all">全选 </label> <label id="reverse"> <input type="checkbox" name="reverse">反选 </label> </div> <pre></pre> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript"> $(function(){ var data = [ '01.大海 ', '02.天路 ', '03.再回首 ', '04.突然的自我 ', '05.甘心情愿 ', '06.光辉岁月 ', '07.雨蝶 ', '08.爱拼才会赢 ', '09.我只在乎你 ', '10..日不落' ]; var html = ''; for(var i = 0; i < data.length; i++){ html += '<li>'+ '<input type="checkbox" name="">'+ '<span>' + data[i] + '</span>'+ '</li>'; } $('#music').html(html); var $all = $('#all input'); var $reverse = $('#reverse input'); var $checkboxEl = $('#music').find('input[type="checkbox"]'); var len = $checkboxEl.length; var n = 0; //input checkbox 选中的个数 $checkboxEl.on('click', function(){ if($(this).attr("checked") == 'checked'){ $(this).attr("checked", false); n--; }else{ $(this).attr("checked", true); n++; } allIsChecked(); }); $all.on('click', function(){ if($(this).attr("checked") == 'checked'){ $(this).attr("checked", false); $checkboxEl.attr('checked', false); $checkboxEl.prop('checked', false); n = 0; }else{ $(this).attr("checked", true); $checkboxEl.attr('checked', true); $checkboxEl.prop('checked', true); n = len; } }); $reverse.on('click', function(){ $checkboxEl.each(function(i, el){ if($(this).attr("checked") == 'checked'){ $(this).attr("checked", false); $(this).prop("checked", false); n--; }else{ $(this).attr("checked", true); $(this).prop("checked", true); n++; } }); allIsChecked(); }); function allIsChecked(){ if(n == len){ $all.attr('checked', true); $all.prop('checked', true); }else{ $all.attr('checked', false); $all.prop('checked', false); } } }) </script> </body> </html>
相关推荐
EdwardSiCong 2020-11-23
85477104 2020-11-17
hhanbj 2020-11-17
81427005 2020-11-11
seoppt 2020-09-13
honeyth 2020-09-13
WRITEFORSHARE 2020-09-13
84483065 2020-09-11
momode 2020-09-11
85477104 2020-08-15
83510998 2020-08-08
82550495 2020-08-03
tthappyer 2020-08-03
84901334 2020-07-28
tthappyer 2020-07-25
TONIYH 2020-07-22
tztzyzyz 2020-07-20
83510998 2020-07-18
81463166 2020-07-17