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

Uncaught ReferenceError: $ is not defined


布局文件-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>


内容页面-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


我希望不要将所有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++;
});


如果查看源代码并从Web服务器检查app.js文件,则可以看到jQuery已加载到app.js文件中。

最佳答案

Laravel默认情况下会加载jQuery,因此除非您将其从已编译的app.js中删除(运行npm命令以从资产进行编译),否则它就会存在。问题是您正在推迟此脚本。页面JavaScript运行后,正在加载jQuery。

尝试删除defer命令。

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

关于javascript - 无法在Laravel Blade文件中使用jQuery,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50185203/

10-11 22:43
查看更多