简单练习,老司机请绕行。
html代码:
<table id="m_table">
<colgroup>
<col style="width:30%;"/>
<col style="width:35%;"/>
<col style="width:35%;"/>
</colgroup>
<tr>
<th><input class="c_all" type="checkbox" /> 全选</th>
<th></th>
<th></th>
</tr>
<tr>
<td><input class="c_one" type="checkbox" /></td>
<td></td>
<td></td>
</tr>
<tr>
<td><input class="c_one" type="checkbox" /></td>
<td></td>
<td></td>
</tr>
<tr>
<td><input class="c_one" type="checkbox" /></td>
<td></td>
<td></td>
</tr>
<tr>
<td><input class="c_one" type="checkbox" /></td>
<td></td>
<td></td>
</tr>
</table>
为使页面好看,加一段css:
* { padding: 0; margin: 0; }
html,body { width: 100%; height: 100%; font-family: 'Arial'; }
table{border-collapse: collapse;}
#m_table { width: 500px; height: auto; color: #333; font-size: 14px; }
#m_table tr th { background: #eaeaea; padding: 10px 30px; text-align: left;}
#m_table tr td { border: 1px solid #eaeaea; padding: 10px 30px; }
正菜如下:
var c_all = document.getElementsByClassName("c_all")[0];
var c_one = document.getElementsByClassName("c_one");
var len = c_one.length;
c_all.onclick = function () {
if( this.checked ){
for(var i = 0; i < len; i++) {
c_one[i].checked = this.checked;
}
}else{
for(var i = 0; i < len; i++) {
c_one[i].checked = false;
}
}
}
for(var i = 0; i < len; i++){
c_one[i].onclick = function(){
fn();
}
}
function fn(){
var arr = [];
for (var i = 0; i < len; i++) {
if (c_one[i].checked) {
arr.push('1');
} else {
arr.push('0');
}
}
if (arr.indexOf('0') >= 0) {
c_all.checked = false;
} else {
c_all.checked = true;
}
}
为保证’getElementsByClassName’能正常运行,最好在代码里加上以下检测代码:
window.onload = function(){
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (cls) {
var ret = [];
var els = document.getElementsByTagName('*');
for (var i = 0, len = els.length; i < len; i++) {
if (els[i].className.indexOf(cls + ' ') >=0 || els[i].className.indexOf(' ' + cls + ' ') >=0 || els[i].className.indexOf(' ' + cls) >=0) {
ret.push(els[i]);
}
}
return ret;
}
}
}
用jQuery改写一下上面的代码:
var $c_one = $(".c_one");
var $c_all = $(".c_all");
var len = $c_one.length;
$c_all.click(function() {
if( $(this).prop("checked") ){
$c_one.prop("checked", "true");
}else{
$c_one.prop("checked", "");
}
});
$c_one.click(function() {
fn();
});
function fn(){
var arr = [];
for (var i = 0; i < len; i++) {
if ($c_one.eq(i).prop("checked")) {
arr.push('1');
} else {
arr.push('0');
}
}
if (arr.indexOf('0') >= 0) {
$c_all.prop("checked", "");
} else {
$c_all.prop("checked", "true");
}
}
下面这种思路是通过绑定类名来实现的,(很巧妙)
$c_one.click(function() {
fn1();
fn2();
});
function fn1(){
$c_one.each(function() {
if( $(this).prop("checked") ){
$(this).addClass('act');
}else {
$(this).removeClass('act');
}
})
}
function fn2(){
var len1 = $(".act").length;
if (len == len1) {
$c_all.prop("checked", "true");
} else {
$c_all.prop("checked", "");
}
}
(完)