2016-10-20 15 views
0

私はフォーラムのエントリをループしています。それぞれの隣に、私はコメントフォームへの返信を表示するか隠すボタンを配置しています。これは単純なJSスクリプト。しかし、スクリプトはループアウトされているため、先頭のスクリプトのみが機能します。 idは一意ではないため(クラスによってすべてが表示/非表示になるため)、idを使って各要素を識別することができないからです。私はidに{{$ comment-> id}}のようなものを追加することを考えていました。それで一意になりますが、私はJSスクリプトを使用できません。私はできますか?foreachループで生成された要素の表示/非表示

以下

関連するコードです:

@extends('layout') 

@section('head') 
<script> 
$(document).ready(function(){ 
    $("#showhidereply").click(function(){ 
     $("#replycomment").toggle(); 
    }); 
}); 
</script> 
@stop 

@section('content') 
    ... 
    <!-- Comments --> 
      @foreach ($post->comments as $comment) 
       <span class="pull-right"> 
        <div class=" btn-group"> 
        <button class="btn btn"> 
         <span class="glyphicon glyphicon-picture"></span> Owner's Name Here 
        </button> 
        <button class="btn btn btn-primary" id="showhidereply"> 
         <span class="fa fa-reply"></span> 
        </button> 
        </div> 
       </span> 
       <p>{{ $comment->body }}</p> 
      </div> 

    <form method="POST" action="/forum/{{ $post->id }}/comments/{{ $comment->id }}/newresponse" id="replycomment"> 
        <input type="hidden" name="_token" value="{{ csrf_token() }}"> 
        <div class="input-group" style="padding-top: 5px;"> 
         <input type="text" name="body" class="form-control"></input> 
         <div class="input-group-btn"> 
         <button type="submit" class="btn btn-primary">Reply to Comment</button> 
         </div> 
        </div> 
        </form> 
        </div> 
      </div> 
      </div> 
     </div> 
     </div> 
      @endforeach 
      </div> 
</div> 
@stop 

私は誰かがへの変更の提案を行う必要がありました:

ボタン

<button class="btn btn btn-primary" class="showhidereply" data-id="{{ $comment->id }}"> 
    <span class="fa fa-reply"></span> 
</button> 

フォーム

<form method="POST" action="/forum/{{ $post->id }}/comments/{{ $comment->id }}/newresponse" id="replycomment-{{ $comment->id }}"> 

スクリプト

<script> 
$(document).ready(function(){ 
    // change the selector to use a class 
    $(".showhidereply").click(function(){ 
     // this will query for the clicked toggle 
     var $toggle = $(this); 

     // build the target form id 
     var id = "#replycomment-" + $toggle.data('id'); 

     $(id).toggle(); 
    }); 
}); 
</script> 

しかし、それでも機能しませんが、要素はすべて一意です。

多くのありがとうございます!

+0

、これを使用してみてください: は//で$キーを使用してコードを書く '@foreach($キー=> $のコメントとして$後>コメント) id @ endforeach' – Alessandro

答えて

0

あなたがフォローのようなインデックスを使用でき

<button class="btn btn btn-primary" data-id="{{ $comment->id }}" onclick="showHide('replycomment-{{ $comment->id }}');"> 
    <span class="fa fa-reply"></span> 
</button> 

//javascript code 
<script> 
    function showHide(id){ 
     $("#"+id).toggle(); 
    } 
</script> 
関連する問題