如果选中复选框,则显示或隐藏表格行

我想在选中复选框时隐藏表行(包含输入字段)。 我找到了有用的东西:

HTML

Hide inputs

脚本

 $(document).ready(function () { $('#checkbox').change(function () { if (!this.checked) $('#row').fadeIn('slow'); else $('#row').fadeOut('slow'); }); }); 

小提琴

但这仅在未选中复选框时才有效。 因此,如果在开头选中复选框,我希望隐藏表格行。 我该怎么做呢?

请注意,我对JavaScript知之甚少,但我确实需要这个

附加事件后触发.change()事件:

 $(function () { $('#checkbox1, #checkbox2').change(function () { var row = $(this).closest('tr').prev(); if (!this.checked) row.fadeIn('slow'); else row.fadeOut('slow'); }).change(); }); 

注意:我缩短了代码。

的jsfiddle

只需在最初注册后调用更改事件:

 $(document).ready(function () { $('#checkbox').change(function () { if (!this.checked) $('#row').fadeIn('slow'); else $('#row').fadeOut('slow'); }); $('#checkbox').change(); }); 

我相信这就是你要找的东西:

 $(function() { var init = true; $('input[type="checkbox"]').change(function() { if (this.checked) { if (init) { $(this).prev().hide(); init = false; } else $(this).prev().slideUp(); } else $(this).prev().slideDown(); }).change(); }); 
 input[type='text'] { display: block; padding: 3px 5px; margin: 5px 0; } 
  
Hide input
Hide input

没有硬编码ID的通用解决方案:

 $('table :checkbox').change(function(e, speed) { speed = typeof speed == 'undefined' ? 'slow' : 0; $(this).closest('tr').prev()[this.checked ? 'fadeOut' : 'fadeIn'](speed); }).trigger('change', [0]); 
  
Hide inputs
Hide inputs

只需在document.ready之后调用change函数

  $('#checkbox').change(); 

像这样

 $(document).ready(function () { $('#checkbox').change(function () { if (!this.checked) $('#row').fadeIn('slow'); else $('#row').fadeOut('slow'); }); $('#checkbox').change(); }); 

这是DEMO FIDDLE

Musefan的答案非常好,但以下也是另一种方式!

 $(document).ready(function () { ($('#checkbox').prop('checked')==true) ? $('#row').fadeOut('slow'):$('#row').fadeIn('slow'); $('#checkbox').change(function () { if (!this.checked) $('#row').fadeIn('slow'); else $('#row').fadeOut('slow'); }); }); 

如果你真的想要最初检查复选框,你最初可以隐藏它们。

 
Hide inputs
 var showOrHideRow=fucntion(isChecked){ if (isChecked) $('#row').fadeOut('slow'); else $('#row').fadeIn('slow'); }; $(document).ready(function () { showOrHideRow($('#checkbox').is(":checked")); $('#checkbox').change(function () { showOrHideRow(this.checked); }); });