# Class/constructor/DOM [TOC] # Class類別 ### 1. Object (1)建立 ``` let movieLaLaLand = { title: "La La Land", year: 2016, director: "Damien Chzelle", time: 128, play: function(){ window.alert(`播放電影:${this.title}`); } }; ``` (2)使用物件 ``` let year = movie1.year; movie1.play(); ``` ### 2. Class概念 (1)當想建立多個電影時,可建立一個公用模板(Class) ``` class Movie { constructor(title, year, director, time){ this.title = title; this.year = year; this.director = director; this.time = time; } play(){ window.alert(`播放電影:${this.title}`); }; } ``` (2)建構子:constructor 建構出Movie物件的初始化function(紅匡處) ![](https://hackmd.io/_uploads/rklaCvCi3.png) 範例DVD工廠 建構式:工廠能幫某部電影出DVD時的製作方式(上圖紅框處相當於告訴工廠機台: 產出的DVD要有以下幾個properties或methods) ![](https://hackmd.io/_uploads/SkF00DAs3.png) 建立物件: 當工廠運行時,會使用以下語法讓機器開始運轉 ![](https://hackmd.io/_uploads/SJjkydAi3.png) ### DOM 1. Document Object Model 文件物件模型 2. html的東西都可以透過這個物件來在js中操作 3. 基本結構:樹狀結構 node:節點 ![](https://hackmd.io/_uploads/BJTxluRjh.png) ![](https://hackmd.io/_uploads/BydWe_Ai3.png) (1)document 整個HTML檔(root code) ![](https://hackmd.io/_uploads/HksHxuRoh.png) (2)element HTML tag (div. p...) ![](https://hackmd.io/_uploads/HJOwg_Cj2.png) (3)text HTML tag 包起來的文字(隸屬於element) ![](https://hackmd.io/_uploads/S1xiYgd0on.png) (4)attribute HTML tag的各種attributes(隸屬於element) ![](https://hackmd.io/_uploads/HkI2euRj3.png) 該HTML的樹狀結構如下: ![](https://hackmd.io/_uploads/HJA6e_0sh.png) DOM操作 取得document ![](https://hackmd.io/_uploads/r1flW_Con.png) 取得element 透過tag(取回多個HTML Collection,類似array) ![](https://hackmd.io/_uploads/BknfWuCi2.png) ![](https://hackmd.io/_uploads/rk0LWO0j3.png) 透過id(取回單個HTML element) ![](https://hackmd.io/_uploads/r1zYWdRin.png) 透過class(取回多個HTML Collection,類似array) ![](https://hackmd.io/_uploads/ryGs-dCo3.png) 透過css selector(取回第一個HTML element) ![](https://hackmd.io/_uploads/H1HXNORoh.png) 透過css selector(取回所有NodeList,類似array) ![](https://hackmd.io/_uploads/SJfIEO0j2.png) NodeList vs HTML Collection 如:透過tag會取回HTML Collection,透過Css Selector則會取回NodeList ![](https://hackmd.io/_uploads/B1u0Nu0jn.png) HTML Collection:只存放Element NodeList:存放所有種類的Node(Element、Test、Attribute) 取得attribute 取出element後,透過attributes property取得 ![](https://hackmd.io/_uploads/Bk5uBu0on.png) 取得text 取出element後,透過inner Text取得 ![](https://hackmd.io/_uploads/rJ9cr_0o3.png) 取出element後,透過innerHTML取得 ![](https://hackmd.io/_uploads/H1QhH_Rj3.png) innerText vs innerHTML HTML結構為多層 ![](https://hackmd.io/_uploads/BkN0r_0j2.png) 透過innerText會拿到最內層的文字 ![](https://hackmd.io/_uploads/HyUyUd0j3.png) 透過innerHTML會拿到所有內層HTML程式碼 ![](https://hackmd.io/_uploads/r1FZLu0sn.png) 新增element document.createElement(要建立的標籤) ![](https://hackmd.io/_uploads/B1E7vd0sh.png) 修改text document.innerText = 文字 ![](https://hackmd.io/_uploads/SJlLPORoh.png) 新增attribute document.setAttribute(name,value) ![](https://hackmd.io/_uploads/H1-_w_Co2.png) 塞入Element到HTML正確位置中 取得parent