如何隐藏jQuery操作的空元素及其父元素

时间:2011-10-27 07:09:14

标签: jquery children

我有一个包含标签/复选框(待办事项)的表格(待办事项列表),如下所示:

<form class="tasklist">
    These are your tasks for today
    <label>
        <input class="task" type="checkbox">
        This is a task that was added by the user
     </label>
     <label>
        <input class="task" type="checkbox">
        This is a task that was added by the user
     </label>
 </form>

当用户检查任务时,使用以下Javascript从DOM中删除它(输入和父标签):

$('input.task').click(function(){
    var checkbox = $(this);
    if (checkbox.prop("checked")) {
       checkbox.parent().css('text-decoration', 'line-through').fadeOut(1000, function(){checkbox.parent().remove();});
    }
});

我希望父表单(.tasklist)在没有更多任务(标签子项)后消失。我对jQuery很新,我尝试了各种方法无效(.tasklist:empty,children('label')。size()== 0等...)

编辑:请注意,可能有多个任务列表表单。

我非常感谢你的帮助。

4 个答案:

答案 0 :(得分:2)

这适用于您提供给我们的代码,我刚刚添加了form.children().length == 0

$('input.task').click(function(){
  var checkbox = $(this);
  var form = $(this).parents('form');
  if (checkbox.prop("checked")) {
     checkbox.parent().css('text-decoration', 'line-through').fadeOut(1000, function(){
         checkbox.parent().remove();
         if(form.children().length == 0) {
           form.remove();
         }
     });
  }
});

JSFiddle Example

答案 1 :(得分:1)

我认为输入应该在标签之外。
编辑:
好吧,我刚刚检查过,它们可以在标签内部,但是可以进行下调?真?评论已经完成,但我认为这并不是那么有趣。


无论如何你可以这样做:

if($('.tasklist label').length == 0){
    $('.tasklist').remove();
}

答案 2 :(得分:1)

示例(使用隐藏而不是删除)
演示 - http://jsfiddle.net/BpFJY/

$('input.task').click(function(){
  var checkbox = $(this);
    if (checkbox.is(':checked')) {
     checkbox.parent().css('text-decoration', 'line-through').fadeOut(1000, function(){
         checkbox.parent().hide();
     });
  }
  if ($('.tasklist input:not(:checked)').length == 0)
      $('.tasklist').hide();
});

答案 3 :(得分:0)

对于第一次编辑感到抱歉..我修复了代码并提供了它的工作示例

您可以为每个表单添加一个数字,如此

<form class="tasklist-1">
 </form>

<span>Next Form</span>

<form class="tasklist-2">
 </form>

然后使用它来检查表单是否已提交!

$('input.task').click(function(){
  var checkbox = $(this);
  var form = $(this).parents('form');
  var fid = form.attr("class").replace("tasklist-","");
    if (checkbox.is(':checked')) {
     checkbox.parent().css('text-decoration', 'line-through').fadeOut(1000, function(){
         checkbox.parent().hide();
     });
  }
  if ($('.tasklist-' + fid + ' input:not(:checked)').length == 0)
      $('.tasklist-' + fid).fadeOut(1000);
});

实例 http://jsfiddle.net/RQjhN/1/