2010-12-03 70 views
2

我要检查或取消选中所有下面的代码对我的作品访问每个

$('#chkboxall').live('change', function() { 

           objs=$(document).find('#chkbox'); 
       objs.each(function(){ 
           $(this).attr('checked', $(this).is(':checked') ? '' : 'checked'); 
      }); 
       }); 

的checkboxs但不是使用$(this).is(':checked') ? '' : 'checked'我想,我已经检查即原来的复选框的状态里面原来的对象$('#chkboxall')的状态。我怎么能在每个内部做到这一点?

Krishnik

回答

3

可以缩短它没有这里的.each()(因为.attr()可以在设定的每一个元素上已经运行):

$('#chkboxall').live('change', function() { 
    $(document).find('#chkbox').attr('checked', this.checked); 
}); 

然而这是无效的,你有重复chkboxid属性无效。给那些元素类,而不是像这样:

<input name="blah" class="chkbox" type="checkbox" /> 

然后在你的代码中使用.class selector

$('#chkboxall').live('change', function() { 
    $('.chkbox').attr('checked', this.checked); 
}); 

对另一些人在不同的情况下找到这一点,才能到一个参考“外this” 一个.each()内,只需设置一个变量,像这样:

$('#chkboxall').live('change', function() { 
    var thing = this; 
    $('.chkbox').each(function(){ 
    //thing = the outer this, the #chkboxall element 
    }); 
}); 
+0

Ť非常感谢Nick的工作,我已经更新了html标记,现在我正在使用class而不是id。再次感谢。 – Nick 2010-12-03 10:43:04