普通网友 2018-03-28 16:23
浏览 133
已采纳

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

I have created a Laravel 5.6 project on my local.

I have <script src="{{ asset('js/app.js') }}" defer></script> in <head>

In one of the views, I tried

<script type="text/javascript">

    jQuery(document).ready(function(){

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

    });

</script>

but it gives me jQuery is not defined error

If I try Bootstrap 4's collapse function, it works fine. Does that mean jQuery is already included?

I have done npm install and npm run dev

My resources/js/app.js requires bootstrap.js which looks like (not full code but top few lines) as below

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

Please advise. I have checked in different browsers to make sure no cache issues etc.

Update

My layouts/app.blade.php structure is like this -

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

and 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条回答 默认 最新

  • du4629 2018-03-28 18:13
    关注

    jQuery loaded via your app.js, which is only loaded once the page is ready because of the defer attribute in your script tag.

    Your inline script tag where you call jQuery(document).ready is loaded as the page renders, therefore executed before the app.js has been loaded. Hence the error, since jQuery is not yet loaded at that time.

    To fix it, simply remove the defer attribute from the script tag.

    The defer attribute is a boolean attribute.

    When present, it specifies that the script is executed when the page has finished parsing.

    For more information about the defer attribute: https://www.w3schools.com/tags/att_script_defer.asp

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?