在blade函数中将php变量传递给js脚本

问题描述 投票:0回答:1
刀片末尾提供的脚本中的 js 函数应根据参数中发送的 ID 显示/隐藏具有特定 id 的 div,但看起来 js 函数不会从刀片接收 php 参数,因为 div 刀片被赋予了不同的 id按预期,但无法从 js 函数访问它们。 我的问题是如何在特定的 div 上使用函数(注意 div 是由具有不同 id 的 foreach 循环创建的)

@foreach($postsList as $post) <div id="post_div_{{$id}}" style="font-weight:bold" class="p-6 bg-white border-b border-gray-200"> @php $id=$post->id; @endphp <strong>{{$post->title}}</strong> <a>Added: {{$post->created_at}}</a> <form method="POST" action="/posts/delete/{{$post->id}}"> <button id="DeleteButton" onclick="deletePost($id)" type="button">Delete</button> </form> <button onclick="editPost($id)" type="button">Edit</button> <div id="all_div_{{$id}}" class="p-6 bg-white border-b border-gray-200" style="display: none;">@include('editPost', ['post'=>$post])</div> <script type="text/javascript"> function deletePost($id) { document.getElementById('post_div_' + { $id }).style.display = "none"; } function editPost($id) { document.getElementById('all_div_' + { $id }).style.display = "block"; } </script> </div> @endforeach
    
javascript php laravel laravel-8 laravel-blade
1个回答
0
投票
您尝试通过将 PHP 变量直接包含在脚本块中来在 JavaScript 函数中使用它们。但是,JavaScript 不会自动解释 Blade/PHP 变量,尤其是大括号内的变量。

@foreach($postsList as $post) @php $id = $post->id; @endphp <div id="post_div_{{$id}}" style="font-weight:bold" class="p-6 bg-white border-b border-gray-200"> <strong>{{ $post->title }}</strong> <a>Added: {{ $post->created_at }}</a> <form method="POST" action="/posts/delete/{{ $post->id }}"> <button id="DeleteButton" onclick="deletePost({{ $id }})" type="button">Delete</button> </form> <button onclick="editPost({{ $id }})" type="button">Edit</button> <div id="all_div_{{ $id }}" class="p-6 bg-white border-b border-gray-200" style="display: none;"> @include('editPost', ['post' => $post]) </div> </div> @endforeach <script type="text/javascript"> function deletePost(id) { document.getElementById('post_div_' + id).style.display = "none"; } function editPost(id) { document.getElementById('all_div_' + id).style.display = "block"; } </script>
每个 post_div_{{ $id }} 和 all_div_{{ $id }} div 都会根据帖子的 $id 获取唯一的 ID。
deletePost({{ $id }}) 和 editPost({{ $id }}) 调用将 $id 传递到 JavaScript 函数中,然后根据动态生成的 ID 访问和操作特定的 div 元素。

© www.soinside.com 2019 - 2024. All rights reserved.