Laravel 5.6 - 我是否需要包含JQuery或者是否已经包含在app.js中?

NoN*_*ice 12 php laravel-5

我在当地创建了一个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>
Run Code Online (Sandbox Code Playgroud)

但它给了我jQuery is not defined错误

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

我已经做了npm installnpm run dev

我的resources/js/app.js要求bootstrap.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) {}
Run Code Online (Sandbox Code Playgroud)

请指教.我已检查过不同的浏览器以确保没有缓存问题等.

更新

我的layouts/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>
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Chi*_*ung 21

jQuery通过你的加载app.js,只有在页面准备好后才会加载,因为defer脚本标记中有属性.

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

要修复它,只需defer从脚本标记中删除该属性即可.

defer属性是布尔属性.

如果存在,它指定在页面完成解析时执行脚本.

有关延迟属性的更多信息:https://www.w3schools.com/tags/att_script_defer.asp

  • 对我来说这个固定的 jQuery 但后来我得到了这个 `app.js:37395 [Vue 警告]:找不到元素:#app` (2认同)