【问题标题】:Laravel 5.6 - Do I need to include JQuery or is it already included in the app.js?Laravel 5.6 - 我需要包含 JQuery 还是已经包含在 app.js 中?
【发布时间】:2021-01-13 00:34:56
【问题描述】:

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

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

在其中一种观点中,我尝试了

<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.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) {}

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

更新

我的 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>

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

【问题讨论】:

  • 这意味着引导程序包括 jquery,我想。
  • 是的,我就是这么想的。不确定这里出了什么问题?
  • app.js 包含在之后你使用你的js代码?
  • 是的。请看我上面的更新。我已经添加了结构。
  • 您需要编译 (laravel.com/docs/5.6/mix#installation) (npm install) 资源并将 app.js (&lt;script src="/js/app.js"&gt;&lt;/script&gt;) 包含到您的视图中

标签: php laravel-5


【解决方案1】:

jQuery 是通过您的 app.js 加载的,由于您的脚本标签中的 defer 属性,它只会在页面准备好后加载。​​

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

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

defer 属性是一个布尔属性。

当存在时,它指定当页面完成解析时执行脚本。

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

【讨论】:

  • 对我来说这个固定的 jQuery 但后来我得到了这个app.js:37395 [Vue warn]: Cannot find element: #app
  • @EugenevanderMerwe 这只是意味着您的 HTML 中没有具有 id="app" 属性的元素。
  • 感谢@Chin Leung 令我沮丧的是这是一个全新的 Laravel 应用程序,为什么会丢失该属性?不过我会再测试一些。
  • @EugenevanderMerwe 默认情况下,Laravel 提供了 JS 以使 Vue 轻松运行,但您必须自己在 DOM 中指定它。否则,如果您不打算使用 Vue,则可以在 app.js 中删除新的 Vue。
  • 过去几天这一直困扰着我。由于延迟,没有加载一个 jquery 插件。删除后一切正常
猜你喜欢
  • 2018-08-14
  • 1970-01-01
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
相关资源
最近更新 更多