---
# System prepended metadata

title: 'JavaScript 學習筆記 - 10: 題型練習: DOM, Event, 陣列, forEach'
tags: [JavaScript 學習筆記]

---

###### tags: `JavaScript 學習筆記`
# JavaScript 學習筆記 - 10: 題型練習: DOM, Event, 陣列, forEach

## HTML內容 (這邊只寫出 body 內的內容)
```
<h2>Add Your Games</h2>
<input type="text" placeholder="Name of The Game" class="gameTitle">
<select class="gameType">
    <option value="Action">Action</option>
    <option value="Sandbox">Sandbox</option>
    <option value="FPS">FPS</option>
<input type="button" class="btn" value="Save">
<h2>The Games</h2>
<div class="filter">
    <input type="button" value="All">
    <input type="button" value="Sanbox">
    <input type="button" value="Open World">
</div>
```

## 整合 innerHTML 資料
```
let data = [];
const list = document.querySelector(".list");
let listStr = "";

data.forEach(funtion(item, index) {
    let content = `<li>${item.name} - ${item.gameType}`;
    listStr += content;
})
list.innerHTML = ListStr;
```
## 初始化: init()
```
function init() {
    const list = document.querySelector(".list");
    let listStr = "";

    data.forEach(funtion(item, index) {
        let content = `<li>${item.name} - ${item.gameType}`;
        listStr += content;
  })
    list.innerHTML = ListStr;
}
init();
```
const list = document.querySelector(".list");
這段也可以放在外層
## 監聽設計
```
const gameFilter = document.querySelector(".filter");
gameFilter.addEventListener("click", function(e) {
    if (e.target.value == undefinded) {
        return;
    }
    let listStr = "";
    data.forEach(function(item, index) {
        if (e.target.value == "All") {
            listStr += `<li>${item.name} - ${item.gameType}`
        }
        else if (e.target.value == item.gameType) {
        listStr += `<li>${item.name} - ${item.gameType}`
        }
    })
})
    list.innerHTML = listStr;
```
## UI 介面邏輯新增
```
const gameTitle = document.querySelector(".gameTitle");
const gameType = document.querySelector(".gameType");
const btn = document.querySelector(".btn");

btn.addEventListener("click", fuction(e){
let obj = {};
obj.Game = gameTitle.value;
obj.Type = gameType.value;
data.push(obj);
gameTitle.value = "";
gameType.value = "Action";
})

```