无法在 Laravel Blade 文件中使用 jQuery

Ron*_*her 0 javascript php jquery laravel

我试图通过在文件中为它定义一个单独的部分来在我的刀片文件中定义我的页面特定的 Javascript。我可以在 app.js 文件中添加相同的 jQuery 代码,它可以正常工作,但是当我将它放入刀片文件时,我收到错误

Uncaught ReferenceError: $ is not defined
Run Code Online (Sandbox Code Playgroud)

布局文件 - app.blade.php

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>
    <script src="{{ asset('js/app.js') }}" defer></script>
    <link rel="dns-prefetch" href="https://fonts.gstatic.com">
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>

<body class="fixed-nav sticky-footer bg-dark" id="page-top">
    <!-- Navigation-->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="mainNav">
        <!-- Nav Stuff -->
    </nav>
    <!--  End Navigation -->
    <!--  Body  -->
    <div class="content-wrapper">
        <div class="container-fluid">
            @yield('content')
        </div>
        <footer class="sticky-footer">
            <!-- footer stuff -->
        </footer>
    </div>
    @yield('script')
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

内容页面 - page1.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <!--  Page Stuff -->            
</div>
@endsection

@section('script')
<script>
    $(document).ready(function()
    {
        alert('hello world');
    });
</script>
@endsection
Run Code Online (Sandbox Code Playgroud)

我不想把我所有的 Javascript 都放在一个 app.js 文件中,我希望能够很好地使用这个部分。直接 Javascript 在这里工作正常,但 jQuery 不行。

编辑:

这是包含 jQuery 库的 app.js 文件。

require('jquery');
require('./bootstrap');
require('jquery-easing');

//  Administration Controller - Add System Type -> This code works just fine.
var numSysDataRows = 5;
$('#add-customer-information').click(function()
{
    $('#system-customer-information').append('<div class="form-group"><label for="col'+numSysDataRows+'">System Data:</label><input type="text" name="col[]" id="col'+numSysDataRows+'" class="form-control" /></div>');
    numSysDataRows++;
});
Run Code Online (Sandbox Code Playgroud)

如果我查看源代码并检查来自 Web 服务器的 app.js 文件,我确实看到 jQuery 已加载到 app.js 文件中。

Goo*_*Mac 5

Laravel 默认加载 jQuery,所以它会在那里,除非你从你编译的 app.js 中删除它(运行 npm 命令从你的资产编译)。问题是您正在推迟此脚本。页面 JavaScript 运行后正在加载 jQuery。

尝试删除 defer命令。

如果这不起作用,请查看 jQuery 是否在您的 app.js 文件中。如果没有,请使用 CDN 或将其复制到您的公用文件夹。