2013-07-25 28 views
0

我有以下代碼。它似乎工作,因爲它會檢查所有的框,然後取消它們。但是,在第一輪之後,它停止檢查和取消選中。它只會檢查一次,並取消選中所有複選框一次。之後,我只有超鏈接纔會顯示並隱藏。JQuery檢查所有鏈接只發生一次

<script type="text/javascript"> 
     function selectAll(){ 
     $("input[type=checkbox]").each(function(){ 
      $(this).attr('checked', true); 
     }); 
     $("#select_all").hide(); 
     $("#unselect_all").show(); 
     } 

     function unselectAll(){ 
     $("input[type=checkbox]").each(function(){ 
      $(this).attr('checked', false); 
     }); 
     $("#select_all").show(); 
     $("#unselect_all").hide(); 
     } 
</script> 
+0

邊注:我建議使用['.prop()'](http://api.jquery.com/prop/),而不是' .attr()'。 – Dom

+0

沒有側面說明。這工作。作爲回答發佈,我會接受。謝謝! – kobaltz

+0

jsfiddle解決最快的方法? –

回答

1

使用.prop(),而不是.attr()

<script type="text/javascript"> 
     function selectAll(){ 
     $("input[type=checkbox]").each(function(){ 
      $(this).prop('checked', true); 
     }); 
     $("#select_all").hide(); 
     $("#unselect_all").show(); 
     } 

     function unselectAll(){ 
     $("input[type=checkbox]").each(function(){ 
      $(this).prop('checked', false); 
     }); 
     $("#select_all").show(); 
     $("#unselect_all").hide(); 
     } 
</script> 
1

嘗試使用attr()prop()而不是爲attr()產生意外結果與檢查屬性中使用時,你並不需要在這裏使用each(),也分配一些class到組複選框,而不是適用於網頁上的所有複選框。您可以使用class selector來選擇具有相同class的複選框(元素)。

function selectAll(){ 
    $("input[type=checkbox]").prop('checked', true); 
    $("#select_all").hide(); 
    $("#unselect_all").show(); 
    } 

    function unselectAll(){ 
    $("input[type=checkbox]").prop('checked', false); 
    $("#select_all").show(); 
    $("#unselect_all").hide(); 
    }