2013-04-16 76 views
5

我试图通过单击表头中的一个复选框来检查/取消选中所有复选框。首先点击添加属性输入,其次取消选中。它只工作一次。在Firefox和Chrome上进行测试。 Аttributes不断变化,但这不会显示在页面中。我只在浏览器调试器中看到它。检查并取消选中输入只能用Jquery工作一次

<table> 
    <thead> 
     <tr> 
      <th><input type="checkbox" /></th> 
      <th>#</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td><input type="checkbox" /></td> 
      <td>1</td> 
     </tr> 
     <tr> 
      <td><input type="checkbox" /></td> 
      <td>2</td> 
     </tr> 
     <tr> 
      <td><input type="checkbox" /></td> 
      <td>3</td> 
     </tr> 
    </tbody> 
</table> 

<script type="text/javascript"> 
$(function() { 
    $('th input[type="checkbox"]').click(function(){ 
     if ($(this).is(':checked')) 
      $('td input[type="checkbox"]').attr('checked', 'checked'); 
     else 
      // $('td input[type="checkbox"]').attr('checked', false); 
      $('td input[type="checkbox"]').removeAttr('checked'); 
    }) 
}); 
</script> 

样品 http://jsfiddle.net/aJhm9/

回答

14

,而是使用属性的属性

$(function() { 
    $('th input[type="checkbox"]').click(function(){ 
     if ($(this).is(':checked')) 
      $('td input[type="checkbox"]').prop('checked', true); 
     else 
      $('td input[type="checkbox"]').prop('checked', false); 
    }) 
}); 

http://jsfiddle.net/aJhm9/2/

+0

它的工作原理!谢谢! – glutaminefree

+0

@АндрейН。别客气。 – Musa

+0

它的工作原理,谢谢!但attr()每次都工作......为什么不现在呢? – brandelizer

3

.attr()仅用于修改元素的默认状态,而不是它的活的状态下使用.prop()的改变元素的活状态。

+0

谢谢。这真的很有用。 – SreenathPG

0

使用prop()代替attr()

$(function() { 
    $('th input[type="checkbox"]').click(function(){ 
    if ($(this).is(':checked')) 
     $('td input[type="checkbox"]').prop('checked', true); 
    else 
     $('td input[type="checkbox"]').prop('checked', false); 
    }) 
}); 

working fiddle

0

为什么使用jQuery这样一个小任务?只需将表格头部的主复选框的ID设置为唯一名称即可。然后将一个特定的类添加到表中的所有其他复选框。然后使用下面的代码: -

var mainCheckbox = document.getElementById('name_of_ID'); 

if(window.addEventListener) { 
    mainCheckbox.addEventListener('change', togglecheckboxes, false); 
} else { 
    mainCheckbox.attachEvent('onchange', togglecheckboxes); 
} 

function togglecheckboxes(){ 
    var otherCheckboxes = document.getElementsByClassName('name_of_CLASS'); //returns an array 
     for(var i = 0; i < otherCheckboxes.length; i++){ 
      otherCheckboxes[i].checked = mainCheckbox.checked; 
     } 
} 
0
<script> 
    $('#select_all').click(function() { 
    $(this).closest('form').find(':checkbox').prop('checked' , this.checked ? true : false); 
}) 
</script>