Laravel 5.6 - 我是否需要包含JQuery,还是它已经包含在应用程序中.js?

2022-08-31 00:33:14

我已经在本地创建了一个Laravel 5.6项目。

我有在<script src="{{ asset('js/app.js') }}" defer></script><head>

在其中一个视图中,我尝试了

<script type="text/javascript">

    jQuery(document).ready(function(){

        jQuery( "#ddtype" ).change(function() {
            alert( "Handler for .change() called." );
        });

    });

</script>

但它给了我错误jQuery is not defined

如果我尝试Bootstrap 4的折叠功能,它可以正常工作。这是否意味着jQuery已经包含在内?

我已经做到了npm installnpm run dev

我的要求,看起来像(不是完整的代码,而是前几行),如下所示resources/js/app.jsbootstrap.js

window._ = require('lodash');
window.Popper = require('popper.js').default;

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.$ = window.jQuery = require('jquery');

    require('bootstrap');
} catch (e) {}

请指教。我已经检查了不同的浏览器,以确保没有缓存问题等。

更新

我的布局/app.blade.php结构是这样的 -

<html>
<head>
....
<!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>
....
</head>
<body>

    <div id="app">

        @include('layouts.nav')

        <main class="py-4">
            @yield('content')
        </main>
    </div>

</body>
</html>

myview.blade.php

@extends('layouts.app')

@section('content')
     .....
     .....
    <script type="text/javascript">

        jQuery(document).ready(function(){

            jQuery( "#ddtype" ).change(function() {
                alert( "Handler for .change() called." );
            });

        });

    </script>
@endsection

答案 1

jQuery 通过 您的 加载,由于脚本标记中的属性,只有在页面准备就绪后才会加载。app.jsdefer

您调用的内联脚本标记在页面呈现时加载,因此在加载之前执行。因此会出现错误,因为当时尚未加载jQuery。jQuery(document).readyapp.js

要修复此问题,只需从脚本标记中删除该属性即可。defer

延迟属性是一个布尔属性。

如果存在此参数,则指定在页面完成分析时执行脚本。

有关“延迟”属性的详细信息:https://www.w3schools.com/tags/att_script_defer.asp


答案 2

推荐