jQuery,讓我們對dom的操作更加便捷。由于其易用性和可擴展性,jQuer也迅速風靡全球,各種插件也是目不暇接。
我相信很多人并不能直接遠離jQuery去做前端,因為它太好用了,我們以前做的東西大多基于jQuery和它的插件。而且現在Angular2的組件生態還不是很完善,我們在編寫Angular的時候也許會想要用到jQuery。本篇文章就簡單介紹下在Angular2中使用jQuery
如果你不知道怎么搭建Angular2開發環境,請參考這篇文章://m.survivalescaperooms.com/article/94934.htm
環境搭好只后先跑起來,然后我們進行下面步驟
首先在index.html中引用jquery,就像我們以前做的那樣

然后我們編寫我們的app.component.ts
import { Component,OnInit} from '@angular/core';declare var $:any;@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent implements OnInit{ ngOnInit() { $("#title").html("<p>this is a string from jQuery html setting</p>"); }}首先需要使用declare生命我們的jQuery,使之成為一個可用的變量,然后,我們需要導入OnInit模塊并實現,我們編寫的jquery代碼就在這里,問中展示了我們向id為title的標簽替換內容,HTML頁面是這樣的
<div id="title" class="title"></div>
然后,接下來的運行效果是這樣的

這就意味著我們可以在Angular2中正常使用jQuery了
接下來做個簡單的jQuery插件使用的例子,首先找一個我們要使用的jQuery插件
首先在index.html 中引用

然后在我們剛才的app.component.ts中的ngOnInit中寫入以下初始化插件代碼
ngOnInit() { $(".card").faceCursor({}); $("#title").html("<p>this is a string from jQuery html setting</p>"); }然后我們編寫html
<div id="title" class="title"></div><div class="container"> <div class="card"> <img src="../assets/me.jpg" style="width:100%;" alt="me"> </div></div>
css
.card{ background: #fff; box-shadow: 0.5em 0 1.25em #ccc; border-radius: .3em; overflow: hidden; max-width: 20em; height: 450px; margin: 0 auto; display: block;}.title{ text-align: center;}.container{ width:100%;}這些工作做了之后,我們運行下,就可以得到以下效果

備注:需要使用到jQuery的地方都要用declare聲明以下,比如其他組件文件中。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答