Не удается прочитать атрибут данных HTML-элемента - PullRequest
0 голосов
/ 06 мая 2019

Я пытаюсь прочитать атрибут postid следующего html-элемента (внутри цикла), но он всегда равен нулю. Я могу напечатать содержимое элемента в консоли инструментов dev (chrome) без каких-либо проблем. Заранее спасибо!

<section class="row posts">
        <div class="col-md-6 col-md-3-offset">
            <header><h3>other posts</h3></header>
            @foreach($posts as $post)
            <article class="post" data-postid = "{{ $post->id }}">
                <p>{{ $post->content }}</p>
                <div class="info">Posted by {{ $post->user->username }} on {{ $post->created_at }}</div>
                <div class="interaction">
                    <a href="#">Like</a>
                    @if(Auth::user() == $post->user)
                        |
                        <a href="#" class="edit">Edit</a> |
                        <a href="{{ route('post.delete',['post_id' => $post->id]) }}">Delete</a>
                    @endif
                </div>
            </article>
            @endforeach
        </div>
    </section>
<script>
        var token = '{{ Session::token() }}';
        var url = '{{ route('edit') }}';
    </script>

Использование следующего javascript для печати в консоли:

var postId = 0;

$('.post').find('.interaction').find('.edit').on('click',function(event){
   event.preventDefault();
   var postBody = event.target.parentNode.parentNode.childNodes[1].textContent;
   postId = event.target.parentNode.parentNode.dataset['postid'];
   $('#post-content').val(postBody);
   $('#edit-post').modal();
});

$('#modal-save').on('click',function(){
   $.ajax({
      method: 'POST',
      url: url,
      data: {body: $('#post-content').val(), postId: postId, _token: token}
   })
    .done(function (msg){
       console.log(msg['message']);
    })
});

Маршрут:

Route::post('/edit', function (\Illuminate\Http\Request $request)
    {
        return response()->json(['message' => $request['postId']]);
    })->name('edit');

Я могу напечатать тело сообщения на консоли, но не повезло с атрибутом postid.

Ответы [ 2 ]

0 голосов
/ 07 мая 2019

Решил, переместив атрибут data-postid из <article class="post"> в <a href="#" class="edit" data-postid="{{ $post->id }}">Edit</a> в html.

После обновления события JavaScript при нажатии на следующее:

$('.post').find('.interaction').find('.edit').on('click',function(event){
   event.preventDefault();
   var postBody = event.target.parentNode.parentNode.childNodes[1].textContent;
   //postId = event.target.parentNode.parentNode.dataset['postid'];
   postId = event.target.dataset.postid;
   $('#post-content').val(postBody);
   $('#edit-post').modal();
});

Спасибо!

0 голосов
/ 06 мая 2019

Вы можете использовать jQuery .closest(), чтобы получить элемент .post, а затем запросить этот элемент.

Кроме того, вам не нужно делать два .find() один за другим. Одного достаточно. Просто укажите правильного ребенка.

$('.post').find('.interaction .edit').on('click',function(event){
   event.preventDefault();
   var post = $(this).closest('.post');
   var postBody = post.find('.info').text();
   postId = post.data('postid');
   $('#post-content').val(postBody);
   $('#edit-post').modal();
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...