2010-12-03 37 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