js及jQuery实现checkbox的全选、反选和全不选

html代码:

<label><input type="checkbox" id="all"/>全选</label>
<label><input type="checkbox" id="other"/>反选</label>
<label><input type="checkbox" id="none"/>不选</label>

<input type="checkbox" value="1" name="check" checked/>
<input type="checkbox" value="2" name="check"/>
<input type="checkbox" value="3" name="check" checked/>

js实现:

window.onload = function(){
        var all = document.getElementById('all');
        var other = document.getElementById('other');
        var none = document.getElementById('none');
        var arr = new Array();
        var items = document.getElementsByName('check');

        all.onclick = function(){
            for(var i = 0;i<items.length;i++){
                items[i].checked = true;
            }
        }
        other.onclick = function(){
            for(var i = 0; i< items.length; i++){
                if(items[i].checked){
                    items[i].checked = false;
                }
                else{
                    items[i].checked = true;
                }
            }
        }
        none.onclick = function(){
            for(var i = 0;i < items.length ;i++){
                items[i].checked = false;
            }
        }
    }

jQuery实现:

$(function(){
       $("#all").click(function(){
           $("input[name='check']").each(function(){
               this.checked = true;
           })
       })
       $("#other").click(function(){
           $("input[name='check']").each(function(){
               this.checked = !this.checked;
           })
       });
       $("#none").click(function(){
           $("input[name='check']").each(function(){
               this.checked = false;
           })
       })
   });

jQuery的实现,一开始写成了$(this)以attr()更改checked属性的方式,如下:

$(function(){
       $("#all").click(function(){
           $("input[name='check']").each(function(){
               $(this).attr({checked:true});
           })
       })
       $("#other").click(function(){
           $("input[name='check']").each(function(){
               $(this).attr({checked:!this.checked});
           })
       });
       $("#none").click(function(){
           $("input[name='check']").each(function(){
               $(this).attr({checked:false});
           })
       })
   });

这种写法在点击了反选或者不选之后,全选和反选都不能正常实现功能。

调用的jQuery版本为jquery-1.11.3.js。查看了jQuery的参考手册,each()中,使用this,指代的是DOM对象,使用$(this)指代的是jQuery对象。

posted @ 2016-05-04 14:02  Viola_left  阅读(286)  评论(0编辑  收藏  举报