我正在编写一个 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 并为每个评论增加它来增加 watch 类和按钮 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');
});
关于Javascript 在循环中切换隐藏和显示按钮 Laravel 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30788841/