実現したいこと
ボタンクリックの際にディベロッパーツールに表示されるUncaught ReferenceError: like is not defined at HTMLButtonElement.onclick というエラーを解決したいです。
前提
LaravelでjQueryとLaravelmixでいいね機能を実装しようとしています。jQueryが導入されているのはクロームの拡張機能で確認済みです。
発生している問題・エラーメッセージ
エラーメッセージ Uncaught ReferenceError: like is not defined at HTMLButtonElement.onclick ((index):23:40)
該当のソースコード
HTML
1<!DOCTYPE html> 2<html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> 3 <head> 4 <meta charset="utf-8"> 5 <!-- Fonts --> 6 <title>TORECON</title> 7 <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet"> 8 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 9 </head> 10 @csrf 11 @foreach($posts as $post) 12 <div class='posts'> 13 <p class='body'>{{ $post->body }}</p> 14 <a href="/posts/{{ $post->id }}">URL</a> 15 <button onclick="like({{$post->id}})">いいね</button> 16 </div> 17 @endforeach 18 <div class='paginate'> 19 {{ $posts->links() }} 20 </div> 21 <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script> 22 <script src="{{ mix('/js/Like.js') }}"></script> 23 </body> 24</html>
Like.js
1 /* global $*/ 2$(document).ready(function () { 3 4 function like(postId) { 5 $.ajax({ 6 headers: { 7 "X-CSRF-TOKEN": document.head.querySelector('meta[name="csrf-token"]').content, 8 }, 9 url: `/like/${postId}`, 10 type: "POST", 11 }) 12 .done(function (data, status, xhr) { 13 console.log(data); 14 }) 15 .fail(function (xhr, status, error) { 16 console.log(); 17 }); 18} 19 20$('button').click(function() { 21 like(1); 22}) 23 24});
試したこと
・ChatGptによるコードの添削
・エラーコードのネット検索
補足情報(FW/ツールのバージョンなど)
jQueryは3.5.1が導入されています。
エラーはボタンをクリックした際にコンソールに出力されます。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2023/10/05 05:15
2023/10/05 06:56
2023/10/06 04:05