需求:table中要求點擊紅色單元格和點擊checkbox的效果同樣,最後一行點擊就是全選、反選、取消選擇的效果。
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> table{ width: 400px; height: 15px; background-color: palegreen; text-align: center; } .check{ width: 20%; background-color: indianred; } input{ display: inline-block; vertical-align:middle; } div{ display: inline-block; width: 400px; } div input{ display: inline-block; width: 20%; } .select{ background-color: bisque; } </style> </head> <body> <table border="1" cellpadding="0" cellspacing="0"> <tr> <td class="check"><input class="inputcheck" type="checkbox"></td> <td>富貴竹</td> <td>綠蘿</td> </tr> <tr> <td class="check"><input class="inputcheck" type="checkbox"></td> <td>梔子花</td> <td>月季</td> </tr> <tr> <td class="check"><input class="inputcheck" type="checkbox"></td> <td>金銀花</td> <td>菊花</td> </tr> <tr> <td class="check check4"><input class="inputcheck" type="checkbox"></td> <td>玫瑰</td> <td>百合</td> </tr> <tr class="select"> <td><input class="selectall" type="button" value="全選"> </td> <td><input class="reserve" type="button" value="反選"> </td> <td><input class="cancel" type="button" value="取消"> </td> </tr> </table> <script> var ele= document.getElementsByTagName("input"); var check= document.getElementsByClassName("check"); var inputcheck= document.getElementsByClassName("inputcheck"); var all = document.getElementsByClassName("selectall")[0]; var reserve = document.getElementsByClassName("reserve")[0]; var cancel = document.getElementsByClassName("cancel")[0]; //for循環閉包 for(var i=0;i<check.length;i++){ var td = check[i]; td.onclick = function () { var td = check[i]; return function () { var input = td.getElementsByTagName("input")[0]; if(input.checked){ input.checked = false; }else { input.checked = true; } } }(i) } //for循環閉包 for(var i=0;i<inputcheck.length;i++){ var input = inputcheck[i]; input.onclick = function () { var input = inputcheck[i]; return function () { if(input.checked){ input.checked = false; }else { input.checked = true; } } }(i) } //全選 all.onclick=function () { for(var i=0;i<ele.length;i++){ ele[i].checked=true; } } //反選 reserve.onclick=function () { for(var i=0;i<ele.length;i++){ if(ele[i].checked){ ele[i].checked=false; } else { ele[i].checked=true; } } } //取消 cancel.onclick =function () { for(var i=0;i<ele.length;i++){ ele[i].checked=false; } } </script> </body> </html>