Javascript 如何在angular中调用外部jQuery函数
我正在从事Angular CLI项目,需要调用一些jQuery函数 我已将我的js包含在angular.json文件中:Javascript 如何在angular中调用外部jQuery函数,javascript,jquery,angular,angular5,Javascript,Jquery,Angular,Angular5,我正在从事Angular CLI项目,需要调用一些jQuery函数 我已将我的js包含在angular.json文件中: "scripts": [ "node_modules/jquery/dist/jquery.min.js", "src/custom.js" ] jQuery函数: function A() { alert('A'); } function B() { alert('B'); } 我已经在组件中导入了jQuery,我需要在其中调用以下jQuery函数:-
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"src/custom.js"
]
jQuery函数:
function A() { alert('A'); }
function B() { alert('B'); }
我已经在组件中导入了jQuery,我需要在其中调用以下jQuery函数:-
import * as $ from 'jquery';
tsconfig.app.json:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"allowJs": true,
"baseUrl": "./",
"module": "es2015",
"types": []
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}
现在,如何在我的组件中导入custom.js以及如何调用这些函数A&B?如果您还没有安装jquery的类型,我建议您安装这些类型:
npm install --save @types/jquery
因此,您只需在组件/服务中导入jQuery(jQuery
)即可使用它:
import 'jquery';
当您在编译或
构建应用程序时遇到问题时,可以通过将选择器包装在(你试过只调用它们吗?不能直接调用..谢谢@Jeffrey,但是你在哪里调用的,我的意思是如何调用它们。我们不能像我一样调用普通的jQuery函数。不需要在组件中导入我的js文件吗?@SunilKumar js文件的导入应该在angular.json文件中完成,你已经纠正了(因此可以全局调用)。您不需要在组件中导入它,只需要使用import'jquery';
(确保您安装了jquery/types)。要调用A/B函数,您应该能够使用($('.myElement')调用它们。A()
ok@Jeffrey让我检查一下,但我有一个疑问,你能解释一下这里的“myElement”是什么吗?你在这里绑定了html元素吗?我能把这些函数作为普通的jQuery函数调用吗?还是需要转换成模块格式?
// Use this
(<any> $('.myElement')).A();
// or this
($('.myElement') as any).A();
import { Component, OnInit, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, AfterViewInit {
constructor(private someService: SomeService) { }
ngAfterViewInit() {
this.someService.someFunction();
}
}