【问题标题】:How to resolve "ReferenceError: $ is not defined"?如何解决“ReferenceError:$ 未定义”?
【发布时间】:2016-12-07 08:20:11
【问题描述】:

我尝试在 angular2 中使用 jquery 并收到此错误:ReferenceError: $ is not defined from the following code.

声明 var $:JQueryStatic;

export class AppComponent {    

ngOnInit() {    

    var container = $("#contact-us-form");    

    container.css("width", $(document).width()).css("height", $(document).height()).hide();    

    container.find(".modal-content .button-close").click(function(){ this.toggleModalWindow("contact-us-form"); });    

    $("#contact-link").click(function(){ this.toggleModalWindow("contact-us-form"); });    

   }     
}      

我该如何解决这个问题?

【问题讨论】:

  • /*Jquery 是使用typings install dt~jquery --global --save 安装的。在 var container = $("#contact-us-form"); 中出现错误表示 $ 未定义的行。 */
  • 您能解释一下声明declare var $:JQueryStatic;的目的吗?
  • 我想用 $.. 所以。其实我想写jquery的东西
  • 嗯...$ 对于 Angular 和 JQuery 来说都是一个非常特殊的字符。尝试使用其他变量名,看看是否仍然出现错误。
  • 我刚刚使用了'Jq',我得到的是'Jq is not defined in [null]'

标签: angular


【解决方案1】:

试试这些步骤-

  1. npm install jquery @types/jquery --save
  2. 进入项目中的angular.json,在脚本中添加“node_modules/jquery/dist/jquery.min.js”:[]。
  3. 重新加载项目。

【讨论】:

    【解决方案2】:

    按照以下步骤操作:

    1. npm i jquery --save
    2. npm i @types/jquery -D
    3. import * as $ from 'jquery'---> 在 app.module.ts 中

    这应该可以解决问题,无需在每个文件中添加 declare var jQuery: any;declare var $: any;

    【讨论】:

    • 步骤有效。请添加一些带有步骤的cmets来解释。
    【解决方案3】:

    添加 angular-cli.json

     "../node_modules/jquery/dist/jquery.js"
    

    有一个打字稿文件

      import * as $ from "jquery";
    

    使用 npm 安装 jquery

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 2017-11-08
      • 2020-10-22
      • 2018-03-20
      相关资源
      最近更新 更多