2017-07-25 50 views
2

我写了一个jQuery函数来添加和删除一些输入,但我得到了这个错误,请帮助我! 我使用jQuery 3.2.1和5.4 Laravel错误删除父母在Laravel 5中使用jQuery

遗漏的类型错误:无法读取属性未定义

这里 '删除' 是我的看法:

@extends('layouts.master') 

@section('content') 
    <script> 
     $(document).ready(function() { 
      $('.add').click(function() { 
       var tr = '<div class="form-group">' + 
        '<label for="title">Title</label>' + 
        '<input type="text" class="form-control" name="title[]" value="{{ old('title') }}">' + 
        '</div>' + 
        '<div class="form-group">' + 
        '<label for="body">Body</label>' + 
        '<textarea class="form-control" rows="10" name="body[]" value="{{ old('title') }}"></textarea>' + 
        '</div>' + 
        '<input type="button" class="btn btn-danger delete" value="x">'; 
       $('.info').append(tr); 
      }); 
      $('.info').on('click', '.delete', function() { 
       $(this).parent.parent.remove(); 
      }); 
     }); 
    </script> 
    <div class="col-sm-8 blog-main"> 
     <h1>Create a post</h1> 
     <hr> 
     <form method="post" action="/blog/posts"> 
      <div class="info"> 
       <div class="form-group"> 
        <label for="title">Title</label> 
        <input type="text" class="form-control" id="title" name="title"> 
       </div> 
       <div class="form-group"> 
        <label for="body">Body</label> 
        <textarea name="body" id="body" class="form-control" rows="10"></textarea> 
       </div> 
       {{csrf_field()}} 
       <input type="button" class="btn btn-danger delete" value="x"> 
      </div> 
      <input type="button" class="btn btn-lg btn-primary add" value="Add New Item"> 
      <button type="submit" class="btn btn-default">Publish</button> 
     </form> 
     @include('layouts.errors') 
    </div> 

@endsection 
+0

它是说$(this).parent.parent.remove(); parent.parent不存在。 –

+0

首先把你的

2

变化
$(document).on('click', '.delete', function() { 
    $(this).parent.parent.remove(); 
}); 

$(document).on('click', '.delete', function() { 
    $(this).parent().remove(); 
}); 
1

你的整个HTML。所以你的代码应该看起来像这样。

var tr = '<div class="parent-div"><div class="form-group">' + 
       '<label for="title">Title</label>' + 
       '<input type="text" class="form-control" name="title[]" value="{{ old('title') }}">' + 
       '</div>' + 
       '<div class="form-group">' + 
       '<label for="body">Body</label>' + 
       '<textarea class="form-control" rows="10" name="body[]" value="{{ old('title') }}"></textarea>' + 
       '</div>' + 
       '<input type="button" class="btn btn-danger delete" value="x"></div>'; 

而不是与此

$(document).on('click', '.delete', function() { 
    $(this).parent().remove(); 
}); 
1

更换您的代码尝试

$(this).closest("input").remove(); 
0

尝试

$(document).on('click', '.delete', function() { 
    $(this).parents('.info').empty(); 
}); 

$(document).on('click', '.delete', function() { 
    $(this).parents('.info').remove(); 
});