AndyChiang
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    5
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # JavaScript 標籤整理 ###### tags: `網頁` `JavaScript` [![](https://img.shields.io/badge/dynamic/json?color=orange&label=總觀看人數&query=%24.viewcount&url=https://hackmd.io/1KVixIIBRrOxkul9m7F_Rw%2Finfo)]() ### 基本HTML範例 ```htmlmixed= <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title></title> <script></script> </head> <body> <p>Hello JavaScript!</p> </body> </html> ``` ### JS 基本認識 JavaScript屬於高階的程式語言,並支援物件導向(OOP),使一部份計算及驗證的功能由用戶端電腦解決,減輕伺服器的計算資源及網路流量。 ##### 基本功能 1. 表單前端認證 2. 動態更改HTML標籤或CSS樣式 3. 動態建立文件內容 4. 增加網頁的互動性 ### JS 套用方法 1. 直接呼叫 > 範例 : JS01.htm ```htmlmixed= <body> <script> //JavaScript 程式碼 </script> </body> ``` 2. 內部載入 ```htmlmixed= <head> <meta charset="utf-8"/> <title></title> <script> function SayHello() { alert("Hello JavaScirpt!"); } </script> </head> <body> <input type="button" value="Hello" onclick="SayHello()"/> </body> ``` 3. 外部載入 > 範例 : JS02.htm ```htmlmixed= <head> <meta charset="utf-8"/> <title></title> <script src="myjs.js"></script> </head> ``` ```javascript= //檔案:myjs.js function SayHello() { alert("Hello JavaScirpt!"); } ``` ### JS 註解 ``` //單行註解寫在這裡 /*多行註解寫在這裡*/ ``` ### JS 變數 - `var 變數名稱` 宣告變數 - 數字(number),包含整數和福點數,如1、20 - 字串(string),"Andy" - 布林常數(boolean),有true和false兩種值 - 物件(object),如{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"} - 未定義(undefined) - `typeof 內容` 傳回內容的屬性 - `let` 區域內的變數,不影響原來的值 - `const` 常數,不可更改 ### JS 數字 JavaScript真不愧是高階語言,超級聰明,數字完全不用管是int還是float,也完全不用擔心溢位問題,因為一個數字用了51個bit存...,編譯器會自己判斷是整數還是小數。 更扯的是,除了加會當作連接字串,字串和字串間竟然可以減乘除 - `NaN` (Not-a-Number)運算結果不為數字時,isNaN()可以檢查 - `Infinity`or`-Infinity` 無限或負無限 - `num.toString(進位)` 轉成指定進位,空白代表10進位,傳回字串 - `num.toExponential()` 轉成科學記號,傳回字串 - `num.toFixed()` 固定小數點位數,傳回字串 - `num.toPrecision()` 固定數字長度,傳回字串 ##### 從String轉成Number - `Number()` 任何變數轉成數字 - `parseInt()` 轉成整數 - `parseFloat()` 轉成小數 ### JS 字串 - `str.length` 取str的長度 - `str.indexOf("day")` 找str中第一個day的首字的位置 - `str.lastIndexOf("day")` 找str中最後一個day的首字的位置 找不到時return=-1 - `str.search("day")` 搜尋day在str中的位置 - `slice(起點, 終點)` 切割成子字串,負號代表顛倒過來 - `substring(起點, 終點)` 切割成子字串,和slice差不多,但不能用負號 - `substr(起點, 長度)` 切割成子字串,從起點開始取指定長度 - `replace(被替換的字串,替換上去的字串)` 替換字串 - 正規表達法,預設為嚴格比對 - /字串/i 寬鬆比對 - /字串/g 全域比對 - `str1.concat(str2)` str1後接上str2 - `str.toUpperCase()` 轉大寫 - `str.toLowerCase()` 轉小寫 - `str.trim()` 幫你削掉多餘的空格 - `charAt(位置)` 回傳指定位置的字元(char) - `split(",")` 依照,做分割 沒錯,你發現了... ... 這不是和Java一樣的函式嗎!? JavaScript和Java真的87%像,學過Java後學JavaScript就會很快上手>< ### JS 陣列 ##### 一維陣列 ``` //建立指定大小的陣列 var 陣列名稱 = new Array(陣列大小); //建立指定元素的值的陣列 var 陣列名稱 = new Array(元素1,元素2,...,元素n); //不建議的寫法 var 陣列名稱 = [元素1,元素2,...,元素n]; //建議的寫法 ``` 元素的值可以是數字,也可以是字串(Chrome不知道為什麼會怪怪的,IE就可以) ##### 二維陣列 ``` var 陣列名稱 = new Array(); 陣列名稱[0] = [元素1,元素2,...,元素n]; 陣列名稱[1] = [元素1,元素2,...,元素n]; . . . 陣列名稱[n] = [元素1,元素2,...,元素n]; ``` ##### 陣列函式 - `Array.isArray(ary)` ary是否為陣列 - `ary.length` 取陣列長度 - `ary.pop()` 取走陣列尾端的內容,回傳值為陣列尾端的內容 - `ary.push("內容")` 將內容加在陣列的尾端,回傳值為新陣列的長度 - `ary.shift()` 取走陣列頂端的內容,回傳值為陣列頂端的內容 - `ary.unshift("內容")` 將內容加在陣列的頂端,回傳值為新陣列的長度 - `delete ary[index]` 將該位置的內容導向undefined - `ary.splice(加入的數量,刪除的數量,欲加入的內容)` 拼接陣列,回傳陣列 - `ary1.concat(ary2)` ary1之後接上ary2,回傳陣列 - `ary.forEach()` 尋訪陣列中的每個元素 - `ary.map()` 依照指定方程式產生新的陣列,回傳陣列 - `ary.filter()` 篩選出符合條件的元素,回傳陣列 - `ary.indexOf("內容")` 尋找該內容的第一個出現位置,回傳數字 - `ary.find()` 尋找符合條件的第一個內容,回傳元素 - `ary.findIndex()` 尋找符合條件的第一個內容的位置,回傳數字 ##### 陣列排序 - `ary.sort()` 依照字串的首字母排序 - `ary.reverse()` 翻轉字串 - 比較數字大小較為麻煩,因為電腦會和字串一樣,從首字母開始比,然而這樣是不對的,所以要改成以下程式碼: ``` ary.sort(function(a, b){return a - b}); ``` - `function(a, b){return a - b}` 比較方程式,兩個兩個來比,如果是負值則a小,如果是正值則a大,依此類推 - 隨機排序 ``` ary.sort(function(a, b){return 0.5 - Math.random()}); ``` - [隨機排序(洗牌算法)](https://hackmd.io/e7Ukj_N2QLu6Ww8s3wFAnQ) - `Math.max.apply(null, arr)` 尋找最大值 - `Math.min.apply(null, arr)` 尋找最小值 - 物件也可以排序 ``` var cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010}]; //依照年份(數字) cars.sort(function(a, b){return a.year - b.year}); //依照品牌名稱(字串) cars.sort(function(a, b) { var x = a.type.toLowerCase(); var y = b.type.toLowerCase(); if (x < y) {return -1;} if (x > y) {return 1;} return 0; }); ``` ### JS 物件 基本上和Java差不了多少 - 定義物件 ``` var 物件名稱 = { 變數名稱1 : 值1, 變數名稱2 : 值2, 函式名稱 : function() { //執行內容 return this.變數名稱1; } }; ``` - 使用物件內的變數 ``` 物件名稱.變數名稱; ``` - 呼叫物件內的函式 ``` 物件名稱.函式名稱(); ``` - `this.變數/函式` 呼叫此範圍內的變數或函式 ### JS 事件 - `<元素 事件="執行內容">` - onclick 按下按鈕時 - onmouseover 滑鼠游標移到物件上時 - onmouseout 滑鼠游標離開物件上時 - onmousedown 長壓住物件時 - onmouseup 長壓後放開物件時 - onload 網頁一完成載入時 - onunload 離開網頁時 - onfocus 滑鼠點擊過後 - onchange 切換元素時 - onkeydown 按下鍵盤時 - `元素.addEventListener("事件",執行內容,事件捕捉/事件泡泡);` 事件監聽 - 事件,就是上面的事件去掉on,如onclick=click - 事件捕捉/事件泡泡,B被包含在A中,false的話,會優先點到B,true則會優先點到A,預設是false,可省略 - 元素.removeEventListener("事件",執行內容); ### JS 常用輸出 - `document.write("欲顯示在網站上的內容")` 印出內容在網站上 可以是文字,也可以是HTML標籤 - `alter("訊息方塊的內容")` 跳出訊息方塊 - 存取HTML元素 ``` var 變數名稱 = document.getElementById("ID名稱"); 變數名稱.value = 欄位值; ``` - `.value` 存取選取清單欄位的內容 - `.selectedIndex` 存取清單第幾個編號 - `.options[i].text` 存取清單第幾個`<option>`標籤上的內容 - `.style.屬性=值` 改變CSS樣式 - `.src='圖片路徑'` 改變圖片 - `.innerHTML` 存取元素的內容或HTML元素 ``` var 變數名稱 = document.getElementById("ID名稱"); 變數名稱.innerHTML = 欲顯示在網站上的內容; ``` - `console.log()` 在執行欄顯示結果 - `window.print()` 列印此頁 ### JS 流程控制 其實就是很簡單的if...else...或for迴圈,跟C和Java學的一模一樣,這邊就不多說了 ##### 選擇敘述 - if...else... - if...else if...else... - 巢狀if - switch ##### 迴圈敘述 - for(初值;終止條件;增值) - while 前測式迴圈 - do...while 後測式迴圈 - 巢狀for - for(x in 物件){} - for(x of 陣列/字串/數字){} ### JS 函式 ``` //定義函式 funciton 函式名稱(引數1,引數2,...,引數n) { //函式主體 return 函式回傳值; } //呼叫函式 函式名稱(引數1,引數2,...,引數n); ``` 引數可以是變數、常數、陣列或物件 ### JS 時間 - `var d = new Date()` 當今時間,回傳物件 - `d.getFullYear()` 取得當今年份,[更多...](https://www.w3schools.com/js/js_date_methods.asp) - `d.setFullYear()` 設定當今年份,[更多...](https://www.w3schools.com/js/js_date_methods_set.asp) ##### 時間格式 - ISO Date : (YYYY-MM-DD) - Short Date : (MM/DD/YYYY) - Long Date : (MMM DD YYYY) - `Date.parse()` 可以將日期轉成毫秒 ### JS 數學運算 - `Math.round(x)` x四捨五入 - `Math.pow(x, y)` x的y次方 - `Math.sqrt(x)` x開根號 - `Math.abs(x)` x的絕對值 - `Math.ceil(x)` 上高斯符號 - `Math.floor(x)` 下高斯符號 - `Math.sin(弧度)` sin,角度要轉成弧度 - `Math.cos(x)` cos,角度要轉成弧度 - `Math.min()` 取最小值 - `Math.max()` 取最大值 - `Math.random()` 從0到1的隨機小數 - `Math.PI` PI常數 - [更多...](https://www.w3schools.com/js/js_math.asp) ### JS 報錯機制 ``` try { Block of code to try } catch(err) { Block of code to handle errors } finally { Block of code to be executed regardless of the try / catch result } ``` - `throw 字串/數字/布林常數` 拋出錯誤 ### JS HTML DOM #### HTML DOM (Document Object Model) ![](https://i.imgur.com/p07tKbh.png) #### 尋找HTML元素 - `document.getElementById(id)` 找到符合id的元素,沒找到回傳null - `document.getElementsByTagName(name)` 找到符合選擇器的元素,沒找到回傳null - `document.getElementsByClassName(name)` 找到符合className的元素,沒找到回傳null #### 改變HTML元素內容 - `element.innerHTML = "內容"` - `element.屬性 = 值` - `element.style.屬性 = 值` - `element.setAttribute( "屬性" , "值" )` 修改屬性值 #### 增減HTML元素(節點) - `document.write("欲顯示在網站上的內容")` 印出內容在網頁上 - `document.createElement(元素)` 創造新元素,創造完一定要呼叫 `document.appendChild(元素)` - `document.appendChild(元素)` 加入新元素 - `document.createTextNode("This is new.")` 加入文字內容 - `document.removeChild(元素)` 移除元素 - `元素.remove()` 移除元素,新版本可用 - `document.replaceChild(新的元素, 舊的元素)` 置換元素 - `document.createAttribute(屬性)` 創造新屬性 ``` var h1 = document.createAttribute(屬性) h1.value = 欲新增的內容 ``` #### 尋找HTML物件(Object) - `document.body` 找到`<body>`元素 - `document.head` 找到`<head>`元素 - `document.querySelectorAll("p")` 找到HTML裡所有的`<p>` [更多..](https://www.w3schools.com/js/js_htmldom_document.asp) #### BOM 節點繼承關係 - `節點.nodeValue` 取節點內的內容 - `節點.nodeName` 取節點的標籤,唯讀 - 如果是元素,回傳標籤名稱,如p、h1 - 如果是屬性,回傳屬性名稱 - 如果是純文字,回傳#text - 如果是根節點,回傳#document - `parentNode` - `childNodes[n]` 第n個節點,從0開始 - `節點[n]` 此節點下的第n個子節點 - `節點.length` 節點下共有幾個子節點 - `firstChild = childNodes[0]` 第一個子節點 - `lastChild` 最後一個子節點 - `nextSibling` - `previousSibling` ### JS JSON JSON是一種資料交換語言,該語言以易於讓人閱讀的文字為基礎,用來傳輸由屬性值或者序列性的值組成的資料物件。 #### JSON的語法 - `"名稱1":"值1"` JSON基本單位 - `{"名稱1":"值1","名稱2":"值2"}` JSON物件 - JSON陣列 ``` "陣列名稱": //物件組成的Array [ {"名稱1":"值1","名稱2":"值2"}, //物件1 {"名稱1":"值1","名稱2":"值2"}, //物件2 {"名稱1":"值1","名稱2":"值2"} //物件3 ] ``` - `var string = JSON.parse(object)` 將JSON型態(object)轉為JSON字串(string) - `var object = JSON.parse("text")` 將JSON字串(text)轉成JS的物件(object)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    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

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully