<div>
<table>
<thead>
<tr>
<th><input type="checkbox" id="sales_checkAll"></th>
<th>商品</th>
<th>价格</th>
<th>数量</th>
</tr>
</thead>
<tbody id="sales_tb">
<tr>
<td><input type="checkbox"></td>
<td>vivo</td>
<td>1999</td>
<td>200</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>huawei</td>
<td>1390</td>
<td>100</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>ipad</td>
<td>3000</td>
<td>200</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>iphone</td>
<td>5000</td>
<td>200</td>
</tr>
</tbody>
</table>
<input type="button" id="btn" value="反选">
</div>
div {
width: 280px;
margin: 100px auto;
}
table {
border-collapse: collapse;
text-align: center;
}
table, th, td {
border: 1px solid #000;
}
th, td {
padding: 5px 10px;
}
#btn {
margin-top: 5px;
}
var sales_checkAll = document.getElementById('sales_checkAll');
var sales_tb = document.getElementById('sales_tb');
var inputs = sales_tb.getElementsByTagName('input');
sales_checkAll.onclick = function () {
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.type === 'checkbox') {
input.checked = this.checked;
}
}
}
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.type !== 'checkbox') {
continue;
}
input.onclick = function () {
checkAllChecked();
}
}
function checkAllChecked() {
var isAllChecked = true;
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.type !== 'checkbox') {
continue;
}
if (!input.checked) {
isAllChecked = false;
}
}
sales_checkAll.checked = isAllChecked;
}
var btn = document.getElementById('btn');
btn.onclick = function () {
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.type !== 'checkbox') {
continue;
}
input.checked = !input.checked;
}
checkAllChecked();
}