劉杰
    • 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
      • Invitee
    • 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
    • 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 Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync 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
Invitee
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
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# JavaScript Crash Course For Beginners --- tags: Javascript relate --- ###### tags: `Javascript` ## 學習大綱以及準備 ### What is Javascript * 高級語言 編譯過的程式語言(不需要編譯器) * 符合ECMAScript的規範 * 多重編程範式 是一種可以支援超過一種編程範式的程式語言。 * 執行於客戶/瀏覽器端同時也作用時伺服器端(Node.js) ### Why learn Javascript * JS是瀏覽器語言 如果你要操作瀏覽器必學 * 建構互動性高的UI藉著React * 建構客戶端的server以及全端的app * 建構行動裝置的app(React Native, NativeScript,Lonic) * 建構桌機端的app(Electron JS) ### What you will learn in this course * 變數&數據型態(Variables & Data Type) * 陣列(Arrays) * 物件實字(object literals) * 操作字串、陣列、物件的方法(Methods for string, arrays, objects,etc) * 迴圈(Loops - for, while, for...of, forEach, map) * 條件式(conditionals - if, ternary&switch * 函式(function&arrow) * 物件導向(OOP-prototype&classes) * DOM選取器介紹(DOM Selection) * DOM操作 * 事件(Events) * 基本的驗證(basic validation) ### 建議可以使用的VScode 配件 可以即時的看做的改變而不用一直做重新整理: ![](https://i.imgur.com/JB1QncD.png) ### 幾種在HTML檔案使用JS的位置 放在body最底層直接撰寫JS程式碼 ```javascript= <body> <header> <h1>JS Crash Course</h1> </header> <script> alert('HEllo world'); </script> </body> ``` 引用到外面的檔案(推薦使用) ```javascript= <body> <header> <h1>JS Crash Course</h1> </header> <script src="main.js"></script> </body> ``` ## Console 印出結果跟debug可以使用的地方 ![](https://i.imgur.com/o0oiise.png) 推薦使用chrome瀏覽器的工具相容性高 ![](https://i.imgur.com/GJlEbeB.png) 一般我們常見的`console.log()`的log的部分其實是方法(methods) [console常見的方法 - MDN](https://developer.mozilla.org/zh-TW/docs/Web/API/Console) ## 變數&數據型態(Variables & Data Type) ### var * 最早版本的變數 * 是全域範圍的變數容易導致衝突 * 現在多已使用下面兩個變數居多 ### let let 可以重新被指派變數 ```javascript= const age = 30; age = 31 console.log(age); ``` ![](https://i.imgur.com/YtZaHI2.png) ### const 作者建議多多使用`const`除非你知道你會使用其他值來做重新指派那就使用`let` const 變數被指派的值不能被改變並且一定要有起始值(initializer)不然會報錯: ```javascript= const age = 30(起始值); age = 31 console.log(age); ``` ![](https://i.imgur.com/4qbuFcC.png) ### Primitive Data Type ```javascript= const name = 'John'; //string const age = 30;//number const rating = 4.5;//number const isCool = true;//boolean const x = null // 代表空的,會跑出object但其實是個錯誤 const y = undefined;//undefined let z; // undefined console.log(typeof name); ``` ### 串接(Concatenation) #### 比較老的字串串接寫法: 當字串較長且變數很多的時候會很痛苦 ```javascript= console.log('my name is ' + name + ' and i am ' + age); ``` #### Template string: 主要使用(~)下面那個符號讓字串串接變的很容易 ```javascript= console.log(`my name is ${name} and i am ${age}`); ``` 甚至可以把它們指派給變數 ```javascript= const hello = `my name is ${name} and i am ${age}`; console.log(hello); ``` #### 字串的methods 計算文字長度(會包含空格) ![](https://i.imgur.com/I0RkgaB.png) ```javascript= const s = 'hello world'; console.log(s.length); ``` #### 轉換至大寫: 這邊的方法因為是function所以需要加上()來做呼叫 (也有轉換到小寫toLowercase) ![](https://i.imgur.com/0T5xOpa.png) ```javascript= const s = 'hello world'; console.log(s.toUpperCase()); ``` #### 擷取文字: ()內的參數代表(起始位置,結束位置) ![](https://i.imgur.com/j87feJH.png) ```javascript= const s = 'hello world'; console.log(s.substring(0, 5)); ``` 方法也可以做串接使用(.) ```javascript= const s = 'hello world'; console.log(s.substring(0, 5).toUpperCase()); ``` #### split: 在參數內是要用來隔開內容的比方說 這邊參數內寫入的是空白因此會得到全部用''隔開的array ![](https://i.imgur.com/arjdTiU.png) ```javascript= const s = 'hello world'; console.log(s.split('')); ``` 如果要把用逗號串接的字串轉換成array的話: ![](https://i.imgur.com/lqvwLmN.png) ```javascript= const s = 'technology, computers, it, code' console.log(s.split(',')); ``` ## 陣列(Arrays) 擁有不只一個value的變數就是array number的array: ![](https://i.imgur.com/r4dYwra.png) ```javascript= const numbers = new Array(1, 2, 3, 4, 5);//new Array這個部分是建構子(constructor) console.log(numbers); ``` 字串的array: ![](https://i.imgur.com/MC7o0p1.png) ```javascript= const fruits = ['apples', 'oranges', 'pears']; console.log(fruits); ``` arrays是以0為基底所以這樣去使用的話會得到: ![](https://i.imgur.com/v1GufuH.png) `console.log(fruits[1]);` 如果要多串一些物件上去可以這樣使用: ![](https://i.imgur.com/TR1FZGh.png) ```javascript= const fruits = ['apples', 'oranges', 'pears']; fruits[3] = 'grapes'; console.log(fruits); ``` 下面是不行的狀況把const變數指派給新的array就會報錯搂 ![](https://i.imgur.com/254TWXS.png) ```javascript= const fruits = ['apples', 'oranges', 'pears']; const fruits = []; console.log(fruits); ``` 然而大多數的情況下你不一定都會知道array裡面的物件數量,所以這時就可以使用 `push`這個methods直接把新的物件加到最後一個位置不管總數為何 ![](https://i.imgur.com/HLK72bw.png) ```javascript= const fruits = ['apples', 'oranges', 'pears']; fruits[3] = 'grapes'; fruits.push('mangos'); console.log(fruits); ``` 如果要把物件加到開頭可以使用`unshift` ```javascript= const fruits = ['apples', 'oranges', 'pears']; fruits[3] = 'grapes'; fruits.push('mangos'); fruits.unshift('strawberries'); console.log(fruits); ``` ### 一些常見的方法: ```javascript= fruits.push('mangos'); //加到最後方 fruits.unshift('strawberries');//加到最前方 fruits.pop();//砍掉最後一個 console.log(Array.isArray(fruits))//檢測是不是arrays 會返回 true or false console.log(fruits.indexOf('oranges'))// 會跑出檢索號碼oranges會跑出 1 ``` ## 物件實字(object literals) 優點是因為封裝的關係可以減少一些全域變數會造成的衝突(不知道是否過時這段說法) 物件實字的語法重點: 會用大括號表示。 裡面的屬性 (Properties) 用鍵值對 (name(key)-value pairs) 表示。ex.(title: ‘Book one’,) 多個屬性以逗號 (comma) 分隔。 宣告完後,還是可以再增加 Properties 進去。 ```javascript= const person = { firstName: 'John',//firsName就是porperty也是key John是value lastName: 'Doe', age: 30, hobbies: ['music', 'movies', 'sports'], address: { street: '50 main st', city: 'Boston', state: 'MA' } } ``` 取得hobbies底下的movies: `console.log(person.hobbies[1])` 取的address底下的city: `console.log(person.address.city)` ### 解構賦值(Destructuring assignment): ES6的東西 可以從array中取出值(value) 可以從object中取出property 並且指派給新的變數 ```javascript= const { firstName,//取出來的值 lastName, address: {//取出來的property city } } = person;//被指派的變數 console.log(city);// 這樣就可以直接取得他的值Boston ``` 加入新的property: ![](https://i.imgur.com/8hVM9wm.png) ```javascript= person.email = '1234@hotmail.com.tw' console.log(person) ``` ### 從array中的物件取得value: 想要取得'Meeting with boss'這個字串的方法如下: ```javascript= const todos = [{ id: 1, text: 'take out trash', isCompeleted: true }, { id: 2, text: 'Meeting with boss', isCompeleted: true }, { id: 3, text: 'Dentist app', isCompeleted: false } ] console.log(todos[1].text) ``` ### 轉換成JSON格式 JSON是一種資料的格式,再傳送資料給server的時候會用JSON這個格式傳跟接收,跟上面物件實字的格式有點像差別在於沒有('')都是(""),並且所以的key的部分都要加上雙引號(""),值的部分除了數字也都要上("") 簡單操作把array轉換成JSON格式使用`JSON.stringify` ![](https://i.imgur.com/TqnR9Tb.png) ```javascript= const todos = [{ id: 1, text: 'take out trash', isCompeleted: true }, { id: 2, text: 'Meeting with boss', isCompeleted: true }, { id: 3, text: 'Dentist app', isCompeleted: false } ] const todoJSON = JSON.stringify(todos); console.log(todoJSON); ``` ## 迴圈(Loops - for, while, for...of, forEach, map) ### For Loop * 第一個分號之前initializes整個loop,同時定義binding * 第二個部分check整個loop要不要繼續跑 * 最後一個部分更新整個loop狀態在每一次迴圈結束之後 ```javascript= for (let i = 0; i < 10; i++) { console.log(i); } ``` ### while Loop 其實跟for很像只是比較囉嗦一點 ```javascript= let i = 0; while (i < 10) { console.log(i); i++; } ``` ### 陣列套用迴圈(loop through arrays) 使用length這個方法就可以取得check要不要跑得部分得數字並使用`todos[i].text`印出文字 ![](https://i.imgur.com/fG7SJTz.png) ```javascript= const todos = [{ id: 1, text: 'take out trash', isCompeleted: true }, { id: 2, text: 'Meeting with boss', isCompeleted: true }, { id: 3, text: 'Dentist app', isCompeleted: false } ] for (let i = 0; i < todos.length; i++) { console.log(todos[i].text); } ``` ### for...of Loop 印出物件`console.log(todo)` ![](https://i.imgur.com/NxLwveS.png) 印出文字`console.log(todo.text)` ![](https://i.imgur.com/qVQMhlP.png) ```javascript= const todos = [{ id: 1, text: 'take out trash', isCompeleted: true }, { id: 2, text: 'Meeting with boss', isCompeleted: true }, { id: 3, text: 'Dentist app', isCompeleted: false } ] for (let todo of todos) {//這邊的todo可以自定義 console.log(todo); } for (let todo of todos) { console.log(todo.text); //這邊一樣可以印出文字 } ``` ### High order array methods(forEach, map, filter) 這邊的high order arrays method都會把一個function當作參數放進去作執行 #### forEach 印出每一個()內的參數以及它的property或是方法 下方的例子會得到每個todo的text ![](https://i.imgur.com/7I7VFM3.png) ```javascript= todos.forEach(function (todo) { console.log(todo.text); }) ``` #### map map會產出一個新的array,下面的範例只產出包含text的array ![](https://i.imgur.com/KahrdhH.png) ```javascript= const todoText = todos.map(function (todo) { return todo.text; }) console.log(todoText); ``` #### filter 會有條件做篩選 下方的條件是todo.isComplete是否為true是的話則印出新的array來包含被篩選後的內容 ![](https://i.imgur.com/HKo2jSB.png) ```javascript= const todoComplete = todos.filter(function (todo) { return todo.isCompeleted === true; }) console.log(todoComplete); ``` #### 綜合使用 下方的例子要使用filter中有true的內容後map出只有text的內容 ![](https://i.imgur.com/67gdQAP.png) ```javascript= const todoComplete = todos.filter(function (todo) { return todo.isCompeleted === true; }).map(function (todo) { return todo.text; }) console.log(todoComplete); ``` ## 條件式(conditionals - if, ternary&switch ### if, else if, else的用法: 符合if的條件跑他的{}不然就往下走跑else if,都不符合則跑else ```javascript= const x = 1; if (x === 10) { console.log('x is 10'); } else if (x > 10) { console.log('x is greater than 10') } else { console.log('x is less than 10'); } ``` ### 邏輯 OR 運算子 (||) 只要有一格成立就可以跑下面的程式 ![](https://i.imgur.com/vJmzenG.png) ```javascript= const x = 4; const y = 11; if (x > 5 || y > 10) { console.log('x is more 10 or y is more than 10'); } ``` ### 邏輯 AND 運算子(&&) 並須兩邊都符合,所以下面的程式碼不會跑 ```javascript= const x = 4; const y = 11; if (x > 5 && y > 10) { console.log('x is more 10 or y is more than 10'); } ``` ### 三元 ternary 運算子(? :) 問號前面是條件 問號代表then : 分號左邊代表條件式成立,右邊是不成立 所以我們看下方的程式可以這樣解釋: color = 如果X大於10那麼則是red,沒有大於的話則是blue ```javascript= const x = 11; const color = x > 10 ? 'red' : 'blue'; console.log(color); ``` ### switch 像開關一樣哪個條件符合則使用哪一段程式碼,記得要加上break跳出迴圈 ![](https://i.imgur.com/Xaf9yKL.png) ```javascript= const x = 21; const color = x > 10 ? 'red' : 'blue'; switch (color) { case 'red': console.log('color is red'); break; case 'blue': console.log('color is blue'); break; default: console.loe('color is not red or blue') break; } ``` ## 函式(function&arrow) * 建構階段(可以預設參數,然後預設參數是可以被呼叫階段的參數取代) * 呼叫階段(如果有預設參數則不需要放參數進去這邊) ```javascript= function addNums(num1, num2) {//建構函式階段 console.log(num1 + num2); } addNums(1, 2);//呼叫函式出來使用並且帶入參數 ``` ![](https://i.imgur.com/ZQzRKtb.png) ```javascript= function addNums(num1=1, num2=2) {//也可以使用預設參數就不需要帶入參數 console.log(num1 + num2); } addNums(5,5); ``` ![](https://i.imgur.com/1QLN11T.png) ### 這樣的寫法會比較常見: 使用return帶入並且在console.log()處呼叫函式 ```javascript= function addNums(num1 = 1, num2 = 2) { return num1 + num2; } console.log(addNums(5, 5)); ``` ### 箭頭函式(arrow function) 會用創建變數的方式取代function字樣並且在{}前面加入箭頭(=>) ```javascript= const addNums = (num1 = 1, num2 = 1) => { return num1 + num2; } console.log(addNums(5, 5)); ``` 如果後方的{}裡面只有一個表達式,甚至可以省略到 reutrn以及 {}(這邊要注意如果要加回來return跟{}要一起加不然會報錯) : ```javascript= const addNums = (num1 = 1, num2 = 1) => num1 + num2; console.log(addNums(5, 5)); ``` 甚至當只有一個參數的時候連前面的()都可以省略: ```javascript= const addNums = num1 => num1 + 5; console.log(addNums(5)); ``` ## 物件導向(OOP-prototype&classes)簡介 ### 物件的構成及基本操作: * 屬性(property) 這就好比車子的廠牌 大小 人的姓名年齡等等各種資訊 * 方法(method) 就像是物件的運行方式,車子的發動、煞車,人的吃飯睡覺行走等等 #### 建構子(constructor): * 建構物件 * 實體化物件 ```javascript= // console.log(addNums(5)); function Person(firstName, lastName, dob) {//建構物件 this.firstName = firstName; this.lastName = lastName; this.dob = dob; } // Instantiate object(實體化物件) const person1 = new Person('John', 'Doe', '4-3-1980'); const person2 = new Person('Mary', 'Smith', '3-6-1970'); console.log(person1.firstName); ``` ### `new Date()`物件來呈現時間 設定方式如下,使用`new Date()`的方式設定就可以使用他的方法瞜! ![](https://i.imgur.com/nyZFrDn.png) `console.log(person2.dob);`因為下方dob被設定好了日期所以會呈現出這些完整的資訊 ![](https://i.imgur.com/DYifrBN.png) ```javascript= function Person(firstName, lastName, dob) { this.firstName = firstName; this.lastName = lastName; this.dob = new Date(dob);//被設定好了!! } const person1 = new Person('John', 'Doe', '4-3-1980'); const person2 = new Person('Mary', 'Smith', '3-6-1970'); console.log(person2.dob); ``` ### 物件內的function 使用 在物件中建立getBirthYear這個funciton,然後在外面呼叫這個函式`console.log(person1.getBirthYear())` `console.log(person1.getFullName());` ![](https://i.imgur.com/feisIyC.png) ```javascript= function Person(firstName, lastName, dob) { this.firstName = firstName; this.lastName = lastName; this.dob = new Date(dob); this.getBirthYear = function () { return this.dob.getFullYear(); } this.getFullName = function () { return `${this.firstName} ${this.lastName}` } } // Instantiate object const person1 = new Person('John', 'Doe', '4-3-1980'); const person2 = new Person('Mary', 'Smith', '3-6-1970'); console.log(person1.getBirthYear()); console.log(person1.getFullName()); ``` ### 把物件的function放到prototype 上面有介紹到了建構function在物件裡面的方法,這邊這個方法比較泛用把function放到prototype裡面 ![](https://i.imgur.com/G8iKLoP.png) 這樣使用的原因是不是每個物件都要使用方法所以直接往外拉出來需要的再去抓取使用就好 ![](https://i.imgur.com/feisIyC.png) ```javascript= function Person(firstName, lastName, dob) { this.firstName = firstName; this.lastName = lastName; this.dob = new Date(dob); } // prototype的使用可以讓方法變的更靈活需要時再取用 Person.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}` } Person.prototype.getBirthYear = function () { return this.dob.getFullYear(); } // Instantiate object const person1 = new Person('John', 'Doe', '4-3-1980'); const person2 = new Person('Mary', 'Smith', '3-6-1970'); console.log(person1.getBirthYear()); console.log(person1.getFullName()); ``` ### ES6 -class 得到的結果跟上方一模一樣只是更好閱讀不同語言的使用者也更看的懂 這就是語法糖(不一樣的包裝一樣的內容物) ![](https://i.imgur.com/A4CbBl6.png) ```javascript= class Person { constructor(firstName, lastName, dob) { this.firstName = firstName; this.lastName = lastName; this.dob = new Date(dob); } getBirthYear() { return this.dob.getFullYear(); } getFullName() { return `${this.firstName} ${this.lastName}`; } } // Instantiate object const person1 = new Person('John', 'Doe', '4-3-1980'); const person2 = new Person('Mary', 'Smith', '3-6-1970'); console.log(person1.getBirthYear()); console.log(person1); ``` ## DOM選取器介紹 (DOM Selection) 操作選取的物件就是DOM在做的事情 document就是HTML檔案也通常是DOM作用的地方 ![](https://i.imgur.com/zoMZWC9.png) ```javascript= console.log(document) ``` ### 取得單一的元素 #### `getElementById` ![](https://i.imgur.com/CG9edMJ.png) ```javascript= // Single element console.log(document.getElementById('my-form')) ``` #### 把抓取到的元素指派給變數 ![](https://i.imgur.com/CG9edMJ.png) ```javascript= const form = document.getElementById('my-form'); console.log(form); ``` #### 比較新的用法`querySeletor` 可以抓取任何物件、class、id、各種tag,但是他是單一的選取器所以只會取得第一個就算他是負數 ![](https://i.imgur.com/KEdRbtu.png) ```javascript= console.log(document.querySelector('h1')) ``` ### 取得複數的元素 #### `querySeletorAll` 作者建議都使用這個因為其他方法比較舊 他抓取出來的物件很像array ![](https://i.imgur.com/Mn2Kjig.png) ```javascript= console.log(document.querySelectorAll('.item')) ``` 也可以使用array的一些方法如`forEach`但不是全部畢竟他不是array ![](https://i.imgur.com/LVRarEe.png) ```javascript= const items = document.querySelectorAll('.item'); items.forEach((item) => console.log(item)); ``` ## DOM操作 ```javascript= //把選取的物件指派給變數方便操作 const ul = document.querySelector('.items'); //刪除選取的物件 ul.remove(); //刪除選取的元素最後一個物件 ul.lastElementChild.remove(); //選取的元素的第一個物件文字內容改變 ul.firstElementChild.textContent = 'Hello' //選取的元素的[1]物件文字內容改變 ul.children[1].innerHTML = 'Brad' //選取的元素的HTML內容改變 ul.lastElementChild.innerHTML = '<h1>HELLO<h1>'; //選取的元素的CSS改變 const btn = document.querySelector('.btn'); btn.style.background = 'red'; ``` ### 事件監聽`addEventListener` 建立事件監聽的方法如下: 在addEventListener後面的參數(事件,事件發生時執行的函式) 印出點擊這個事件 ![](https://i.imgur.com/CUxT9m9.png) ```javascript= const btn = document.querySelector('.btn'); btn.addEventListener('click', (e) => { e.preventDefault(); console.log('click') }) ``` 印出所有事件的屬性(attribute) ```javascript= const btn = document.querySelector('.btn'); btn.addEventListener('click', (e) => { e.preventDefault(); console.log(e) }) ``` `console.log(e.target)`這個屬性可以印出e所taget地方的元素像這邊就是點擊哪邊就印出哪邊的元素 ```javascript= const btn = document.querySelector('.btn'); btn.addEventListener('click', (e) => { e.preventDefault(); console.log(e.target) }) ``` `console.log(e.target.className)`可以繼續使用屬性像這邊就可以取得className ```javascript= const btn = document.querySelector('.btn'); btn.addEventListener('click', (e) => { e.preventDefault(); console.log(e.target.className) }) ``` ## DOM實例 實作一個小小的提交表 點擊送出的時候會在下方產生區塊顯示剛剛submit的內容 HTML: ```htmlembedded= <body> <header> <h1>JS For Beginners</h1> </header> <section class="container"> <form id="my-form"> <h1>Add User</h1> <div class="msg"></div> <div> <label for="name">Name:</label> <input type="text" id="name"> </div> <div> <label for="email">Email:</label> <input type="text" id="email"> </div> <input class="btn" type="submit" value="Submit"> </form> <ul id="users"></ul> <!-- <ul class="items"> <li class="item">Item 1</li> <li class="item">Item 2</li> <li class="item">Item 3</li> </ul> --> </section> <script src="main.js"></script> </body> ``` ### 教學一些小技巧 #### 點擊時產生效果 點擊前 ![](https://i.imgur.com/Z30jXcH.png) 點擊後 ![](https://i.imgur.com/19S3u6f.png) ### 事件(Evemt) ```javascript= const btn = document.querySelector('.btn'); btn.addEventListener('click', (e) => { e.preventDefault(); document.querySelector('#my-form').style.background = '#ccc' }) ``` 使用`classList.add()`裡面放入預先做好的class內容就可以在點擊的時候跳出這個被景色 ![](https://i.imgur.com/dQfkMQE.png) ![](https://i.imgur.com/Rf87eeN.png) ```javascript= const btn = document.querySelector('.btn'); btn.addEventListener('click', (e) => { e.preventDefault(); document.querySelector('#my-form').style.background = '#ccc' document.querySelector('body').classList.add('bg-dark') }) ``` 改變文字內容當點擊的時候 ![](https://i.imgur.com/uJ9jciN.png) ```javascript= document.querySelector('.items').lastElementChild.innerHTML = '<h1>hello</h1>' ``` ### 正式內容: ![](https://i.imgur.com/M8fHz33.png) [完成品](https://chiehLiu.github.io/git-projects/JSCCFB/index.html) 第一步把所有的DOM elements轉換成變數 ```javascript= // USER FORM SCRIPT // Put DOM elements into variables const myForm = document.querySelector('#my-form'); const nameInput = document.querySelector('#name'); const emailInput = document.querySelector('#email'); const msg = document.querySelector('.msg'); const userList = document.querySelector('#users'); ``` 加入事件監聽,並建立變數指派給onSubmit這個function並把其內容寫在下方 ```javascript= myForm.addEventListener('submit', onSubmit); ``` 這邊因為想要取得名字的值 可以使用 想要取得值的 `變數.value` ```javascript= function onSubmit(e) { e.preventDefault(); console.log(nameInput.value); } ``` ## 事件的驗證(Event Validation) ```javascript= function onSubmit(e) { e.preventDefault(); if(nameInput.value === '' || emailInput.value === '') { // 下方的msg處理警告文字並且加入額外寫好的CSS msg.classList.add('error'); msg.innerHTML = 'Please enter all fields'; // 計時3 秒鐘 移除警告 setTimeout(() => msg.remove(), 3000); } else { // 如果不是上面的狀況則創造新的<li>元素 const li = document.createElement('li'); // 處理新的<li>裡面的文字內容 li.appendChild(document.createTextNode(`${nameInput.value}: ${emailInput.value}`)); // Add HTML // li.innerHTML = `<strong>${nameInput.value}</strong>e: ${emailInput.value}`; // 把剛剛新增的<li>加到userList裡面 userList.appendChild(li); // 讓他預設為空所以在做完任何動作之後會恢復空白 nameInput.value = ''; emailInput.value = ''; } } ```

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