简体   繁体   English

使用jQuery的自定义JavaScript代码在Angular 5(angular-cli)中不起作用

[英]Custom javascript code using jQuery is not working Angular 5 (angular-cli)

I am building an application using Angular 5 with angular-cli. 我正在使用带有angular-cli的Angular 5构建应用程序。 I've written custom functions using jquery and these functions are not working. 我已经使用jquery编写了自定义函数,但这些函数不起作用。 Let me tell what I've done. 让我告诉我我做了什么。

steps: 脚步:

  1. Have installed jquery using below commands 使用以下命令安装了jQuery

    npm install --save jquery npm install-保存jQuery
    npm install @types/jquery --save ( i know this is for intellisense in typescript) npm install @ types / jquery --save(我知道这是针对打字稿中的intellisense的)

  2. Created a file main.js where i kept all of my custom functions 创建了一个文件main.js,其中保留了所有自定义函数

  3. referred jquery in .angular-cli.json as below 如下引用.angular-cli.json中的jquery

    scripts:[ 脚本:[
    "../node_modules/jquery/dist/jquery.js", “ ../node_modules/jquery/dist/jquery.js”,
    "assets/js/main.js" ] “资产/js/main.js”]

now the function below (i picked one of the functions) in main.js is not working. 现在main.js中的以下功能(我选择了其中一个功能)不起作用。

$( '.search__open' ).on( 'click', function () {
    $( 'body' ).toggleClass( 'search__box__show__hide' );
    return false;
  });

the class .search__box__show__hide has to be appended to body which is not happeing. 必须将.search__box__show__hide类添加到不具有快感的正文中。 I googled, been through many articles in stackoverflow and followed best suggestions to use external libraries such as jquery in angular-cli but no luck. 我用Google搜索,遍历了stackoverflow中的许多文章,并按照最佳建议使用了外部库,例如angular-cli中的jquery,但没有运气。

if I use the below code (which is part of above code fragment) in one of my component then it is working fine. 如果我在我的组件之一中使用下面的代码(这是上面代码片段的一部分),则它工作正常。

$( 'body' ).toggleClass( 'search__box__show__hide' );  

which means $ is recognized from jquery but the same is not working from main.js file. 这意味着$可以从jquery中识别出来,但在main.js文件中却无法使用。

Please let me know what I've been doing wrong, your help is highly appreciated. 请让我知道我做错了什么,我们非常感谢您的帮助。

I found the solution. 我找到了解决方案。

The problem was all of htmls referred as templateUrls in component are rendered later the scripts referred using script tags are evaluated. 问题是组件中所有被称为templateUrl的html都会在稍后渲染使用脚本标记引用的脚本时呈现。 The solution is, use 'defer' on script tag to make sure these scripts are evaluated after the page is loaded. 解决方案是,在脚本标签上使用“ defer”以确保在加载页面后对这些脚本进行评估。

Before: 之前:

<html>
   ......
   <body>
        <app-root></app-root>
        <script src="main.js"></script>
   </body>
<html>

After: 后:

<html>
   ......
   <body>
        <app-root></app-root>
        <script src="main.js" defer></script>
   </body>
<html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM