2017-06-02 50 views
0

我想顯示/隱藏每條評論的回覆。爲了做到這一點,我的jQuery選擇器必須是變量類名(這樣我才能顯示/隱藏特定註釋的回覆而不影響其他註釋的回覆)。我已經寫了PHP代碼附加comment_id與類,使類不同。但是我從Laravel blade loop得到這些ID,我不知道如何在jQuery中做同樣的事情。這裏是我的blade.php -如何從laravel blade loop獲取jQuery的變量類名

@foreach($comments as $comment) 
    <div class="box-comment"> 
    <div class="comment-text"> 
     {{$comment->body}}<br /> 
     <button class="btn btn-link text-muted toggle-replies-{{$comment->id}}">Show/Hide Replies</button> 
    </div> <!-- /.comment-text --> 
    </div> <!-- /.box-comment --> 
    <div class="box-comment reply-box-{{$comment->id}} initially-hidden" style="padding-left: 30px;"> 
    <input type="text" placeholder="Write a reply..."> 
    </div> 
    @foreach($comment->replies as $reply) 
    @if($comment->id == $reply->comment_id) 
     <div class="box-comment reply-box-{{$comment->id}} initially-hidden" style="padding-left: 30px;"> 
     <div class="comment-text"> 
      {{$reply->body}} 
     </div> <!-- /.comment-text --> 
     </div> <!-- /.box-comment --> 
    @endif 
    @endforeach      
@endforeach    

這是jQuery的:

<script> 
$(document).ready(function() { 
    $(".toggle-comments").click(function(){ 
    $(".comment-box").slideToggle(); 
    }); 

    $(".toggle-replies-1").click(function(){ 
    $(".reply-box-1").slideToggle(); 
    }); 
}); 
</script> 

我手動把「1」存在,並且顯示/隱藏第一條評論的答覆。我需要爲所有評論做到這一點。這應該不難,但我仍然在學習jQuery。我希望有人能幫助我。

回答

1

試試這個:

@foreach($comments as $comment) 
    <div class="box-comment"> 
     <div class="comment-text"> 
      {{$comment->body}}<br /> 
      <button class="btn btn-link text-muted show_hide_replies" id="{{$comment->id}}">Show Replies</button> 
     </div> 
    </div> 
    <div class="box-comment reply-box-{{$comment->id}} initially-hidden" style="padding-left: 30px;"> 
     <input type="text" placeholder="Write a reply..."> 
    </div> 
    @foreach($comment->replies as $reply) 
     @if($comment->id == $reply->comment_id) 
      <div class="box-comment reply-box-{{$comment->id}} initially-hidden" style="padding-left: 30px;"> 
       <div class="comment-text"> 
        {{$reply->body}} 
       </div> 
      </div> 
     @endif 
    @endforeach      
@endforeach    

<script type="text/javascript"> 
$(document).ready(function() { 
    $(".toggle-comments").click(function(){ 
     $(".comment-box").slideToggle(); 
    }); 

    $(".show_hide_replies").click(function(ev) { 
     var getElem = $(this).attr("id"); 
     $(".reply-box-"+getElem).slideToggle() 
     $(this).text(function(i, text){ 
      return text === "Show Replies" ? "Hide Replies" : "Show Replies"; 
     }) 
    }) 
}); 
</script> 
+0

謝謝,它的作品的權利。你能幫我多一點嗎?我想要更改按鈕文本切換。如果顯示回覆,我希望按鈕說「隱藏回覆」。否則,應該說「顯示回覆」 –

+1

是的,你可以。查看更新後的答案。 –