Javascript 在循环中切换隐藏和显示按钮 Laravel 5.

Javascript toggle hide and show buttons in a loop Laravel 5

本文关键字:显示 按钮 Laravel 隐藏 循环 Javascript      更新时间:2023-09-26

>我正在编写一个Laravel 5项目,下面有一个注释部分代码

@foreach($Comment as $Comment)
  <div id="comment-{!! $Comment->comments_id !!}" class="comment-wrapper">
     <div class="btn btn-lg btn-info btn-xs" class="show">Show</div>
  <div class="btn btn-lg btn-success btn-xs" class="hide">Hide</div>
  <div class="btn btn-lg btn-warning btn-xs" class="toggle">Toggle</div>
      <div class="watch" class="jumbotron alert-info">

         <ul class="list-group">
           <li class="list-group-item list-group-item-success">{!! $Comment->author  !!}</li>
           <li class="list-group-item"> {!! $Comment->text !!}</li>
           </ul>
             @if ($Comment->author == Auth::user()->name)
               <p><a href="{!! URL::route('deleteComment', $Comment->comments_id) !!}"  class=" btn-danger btn-xs" style="float:right">Delete</a></p>  

              @endif
        <h6><small>CREATED ON: {!! $Comment->created_at !!}</small></h6>
</div>
</div>
          @endforeach

我有一个看起来像这样的javascript文件

 $(document).ready(function () {
 $('.show').click(function () {
    $(this).closest('.comment-parent').find('.watch').show('slow');
});
 $('.hide').click(function () {
    $(this).closest('.comment-parent').find('.watch').hide('slow');
});
 $('.toggle').click(function () {
    $(this).closest('.comment-parent').find('.watch').toggle('slow');
});
});

问题是切换/隐藏javascript功能仅适用于一组按钮并隐藏所有注释。 我想让一组按钮单独适用于每条评论。 我试图通过添加 1 并为每个评论递增来增加手表类和按钮div id,但无法让它工作。 任何帮助将不胜感激。

你可以尝试这样的事情:

$('#show').click(function () {
    $(this).next('.watch').show('slow');
});

对其他方法尝试相同的方法,因此只会执行下一个具有watch类的第一个div,而且,除了class之外,您还可以使用唯一的id属性将每个集合包装在单个父容器中,以便更好地分组。例如:

@foreach($Comment as $Comment)
    <div id="comment-{{$comment->id}}" class="comment-wrapper">
        <div class="btn btn-lg btn-info btn-xs show">Show</div>
        <!-- More... -->
        <div class="watch" class="jumbotron alert-info">
            <!-- More... -->
        </div>
    </div>
@endforeach

这样,您就可以更具体地完成jQuery,例如:

$('#show').click(function () {
    $(this).closest('.comment-parent').find('.watch').show('slow');
});

更新(感谢 haakym 指出我): 此外,id必须是唯一的,因此不要使用它id='show'而是将其用作类,然后使用:

$('.show').click(function () {
    $(this).closest('.comment-parent').find('.watch').show('slow');
});