javascript - 无法在 Laravel Blade 文件中使用 jQuery

标签 javascript php jquery laravel

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

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 或将其复制到您的公共(public)文件夹。

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

相关文章:

javascript - Codeigniter 中的动态选择选项

php - 从一个表中选择与另一表中的值匹配的不同且随机的行

php - 使用复选框从 mysql 中删除多行

javascript - jstree 设置节点 href 链接并添加 onclick 事件

jquery - 图片导致水平滚动

javascript - 在javascript中连续绘制多个圆弧时删除线条

JavaScript 属性更改事件

javascript - VBA for Excel,如何加载 .js 文件作为 Jscript Scriptcontrol 对象

php - WordPress 循环 : how to wrap each 3 posts into a div?

javascript - 专用 jQuery AJAX 函数中的错误回调