js核取方塊全選和取消全選效果

admin發表於2017-05-08

分享一段程式碼例項,它利用原生JavaScript實現了核取方塊的全選和不全選效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
* {
  padding: 0;
  margin: 0;
}
#_head {
  background-color: green;
}
#_head {
  text-align: center;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
  border: 1px solid #c0c0c0;
  width: 300px;
}
th,td {
  border: 1px solid #d0d0d0;
  color: #404060;
  padding: 10px;
}
th {
  background-color: #09c;
  font: bold 16px "微軟雅黑";
  color: #fff;
}
td {
  font: 14px "微軟雅黑";
  text-align: center;
}
</style>
</head>
<body>
<div id="wrapbox">
  <table>
    <thead id="_head">
      <tr>
        <th><input type="checkbox" id="qx"></th>
        <th>菜名</th>
        <th>廚師</th>
        <th>價格</th>
      </tr>
    </thead>
    <tbody id="_tbody">
      <tr>
        <td><input type="checkbox"></td>
        <td>紅燒魚</td>
        <td>張一</td>
        <td>18</td>
      </tr>
      <tr>
        <td><input type="checkbox"></td>
        <td>紅燒肉</td>
        <td>張二</td>
        <td>18</td>
      </tr>
      <tr>
        <td><input type="checkbox"></td>
        <td>紅燒獅子頭</td>
        <td>張三</td>
        <td>18</td>
      </tr>
      <tr>
        <td><input type="checkbox"></td>
        <td>紅燒小青菜</td>
        <td>張四</td>
        <td>18</td>
      </tr>
    </tbody>
  </table>
</div>
<script>
var qx = document.getElementById('qx');
var tbody = document.getElementById('_tbody')
var inputs = tbody.getElementsByTagName("input");

qx.onclick = function() {
  for (var i = 0; i < inputs.length; i++) {
    var input = inputs[i]
    input.checked = qx.checked;
  }
}
for (var i = 0; i < inputs.length; i++) {
  var input = inputs[i];
  input.onclick = function() {
    var flag = true;
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      if (input.checked == false) {
        flag = false;
      }

      if (flag == true) {
        qx.checked = true;
      } else {
        qx.checked = false;
      }
    }
  }
}
</script>
</body>
</html>

相關文章