2016-11-09 90 views
2

全部 我正在製作一個使用Angular 2的小型Web應用程序,並且我想在其中使用JQuery。 我得到在Chrome中的錯誤,我不知道爲什麼 以下是錯誤:

core.umd.js:3004 EXCEPTION: Uncaught (in promise): Error: Error in `enter code here`http://localhost:3000/app/dashboard.component.js class DashboardComponent_Host - inline template:0:0 caused by: $ is not defined 
ReferenceError: $ is not defined 
    at DashboardComponent.ngOnInit (http://localhost:3000/app/dashboard.component.js:22:9) 
    at Wrapper_DashboardComponent.detectChangesInInputProps (/AppModule/DashboardComponent/wrapper.ngfactory.js:18:53) 
    at _View_DashboardComponent_Host0.detectChangesInternal (/AppModule/DashboardComponent/host.ngfactory.js:30:32) 
    at _View_DashboardComponent_Host0.AppView.detectChanges (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:9305:18) 
    at _View_DashboardComponent_Host0.DebugAppView.detectChanges (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:9410:48) 
    at ViewRef_.detectChanges (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:7398:24) 
    at RouterOutlet.activate (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:3458:46) 
    at ActivateRoutes.placeComponentIntoOutlet (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:2955:20) 
    at ActivateRoutes.activateRoutes (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:2933:26) 
    at eval (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:2902:23) 

這裏是我的代碼:

import { Component, ElementRef, OnInit } from '@angular/core'; 
declare var $:JQueryStatic; 
@Component({ 
    moduleId: module.id, 
    selector: 'my-dashboard', 
    templateUrl: 'dashboard.component.html', 
    styleUrls: ['dashboard.component.css'], 
}) 
export class DashboardComponent implements OnInit{ 

    constructor(private elRef: ElementRef){} 

    ngOnInit():any{ 
     $(this.elRef.nativeElement).find('button').on('click', function() { 
      alert('It works!'); 
     }); 
    } 
} 

我用這個答案來安裝jQuery和做一切都如解釋,但不起作用。 link 任何想法爲什麼? 感謝


FIX 我固定它通過改變declare var $:JQueryStatic;declare var $:any; 並列入<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>index.html

+0

您是否嘗試過類似的 'jQuery的''進口$;'? –

+0

@DanielD我剛剛做了,它說'模塊「jquery」沒有默認導出。「#: –

+0

Check out this post:http://stackoverflow.com/questions/35223977/jspm-jquery-typescript-module-jquery- has-no-default-export –

回答

-1

請檢查是否jquery.js使用Chrome開發者工具,例如實際加載。如果沒有,那麼在模塊加載器配置中缺少依賴關係。

您必須確保jquery.js依賴關係對選定的模塊加載器是已知的。

+0

好的,我在'package.jason'聲明爲''jquery「:」^ 3.1.1「'我應該以某種方式安裝嗎? –

+0

@JakubBadacz你從哪裏開始?你能分享你的代碼嗎?很難猜測你的實際設置;) – wzr1337

+0

它沒關係,我想通了:) –

1

使用CDN上layout.cshtml

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js" ></script>