# jQuery入門筆記 筆記參考:https://hackmd.io/@david9806028/ByHtEw8JK 書籍參考:https://www.books.com.tw/products/0010672352 jQuery字典:https://oscarotero.com/jquery/ ## 基本語法 $(selector).action() > $(指定某物件).action(下達指令) <span style=color:red>jQuery 語法是通過選取HTML 元素,並對選取的元素執行某些操作。</span> 美元符號定義jQuery 選擇符(selector)"查詢"和"查找" HTML 元素 jQuery 的action() 執行對元素的操作 ### 實例 ``` $(this).hide() - 隱藏當前元素 $("p").hide() - 隱藏所有<p> 元素 $("p.test").hide() - 隱藏所有class="test" 的<p> 元素 $("#test").hide() - 隱藏所有id="test" 的元素 ``` ## jQuery使用前置作業 先下載 [jQuery Library](http://jquery.com/download/) 接著將此 JS 檔放進你網頁 HTML 的 <head> 及 </head> 之間 `<script src="你的 jQuery 檔案路徑"></script>` 或者透過 Google CDN 載入 jQuery (好處:免費、快) `<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>` ### 文檔就緒後再執行jQuery ``` $(document).ready(function(){ }); ``` <span style=color:red>↓↓↓可簡化成↓↓↓</span> ``` $(function(){ //開始寫jQuery代碼... }); ``` 如果在文檔沒有完全加載之前就運行函數,操作可能失敗。 下面是兩個具體的例子: 1. 試圖隱藏一個不存在的元素 2. 獲得未完全加載的圖像的大小 ## [常用屬性語法](https://hackmd.io/@RongQi/S1Wd8qBws) ``` $('a').hide() /*隱藏a連結*/ $('a').show() /*顯示a連結*/ $('a').attr('href','http://www.yahoo.com.tw') /*attr是增加屬性的意思*/ $('a').slideUp()/*讓a連結被刪除*/ $('a').slideUp(5500)/*讓a連結經過5500(5.5秒)毫秒被刪除*/ $('a').slideDown()/*讓a連結被新增*/ $('a').fadeOut(8000)/*讓a連結經過8000毫秒(8秒)淡出*/ $('button').click(function (e) { /*讓按鈕可以有點擊效果*/ $('a').hide()/*按完按鈕後隱藏*a連結*/; }; $('button').click(function (e) { /*讓按鈕可以有點擊效果*/ $('a').toggle() /*自動幫你切換開關,搭配按鈕可以做出消失出現切換*/; }; $('a').slideToggle() /*在toggle的基礎上加上slideup和slidedown效果*/; $('a').fadeToggle() /*在toggle的基礎上加上fadein和fadeout效果*/; $('h1').click(function (e) { $('p').addClass('red'); /*動態增加css*/ }); $('h1').click(function (e) { $('p').toggleClass('red'); /*用toggle方式增加css*/ }); $('a').attr('href','http://www.yahoo.com.tw'); /*attr是更改屬性,更改了'href'屬性的內容'網址'*/ ``` ## jQuery 選擇器 $("*") :選取全部 $(this):選取當前元素 $("p:first"):選取第一個`<p>`元素 $("ul li:first"):選取第一個ul的第一個li元素 $("ul li:first-child"):選取每一個ul的第一個li元素
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up