---
# System prepended metadata

title: todolist經典題目實作
tags: [Javascript]

---

---
tags: Javascript
---

# todolist經典題目實作

在開始之前先將他拆解成各個小功能，需要取值，監聽按鈕，新增，刪除

## 資料初始化渲染

創建一個`todolist.html`

```htmlembedded=
<html>
  <head>
    <title>Js todolist</title>
  </head>
  <body>
    <input type="text" placeholder="輸入待辦事項" class="txt" />
    <input type="button" class="create" value="新增待辦" />
    <ul class="todo-list"></ul>
    <script src="index.js"></script>
  </body>
</html>
```

創建`index.js`
```javascript=
// 創建初始資料
let data = [
      {
    content: "起床",
      },
      {
        content: "吃早餐",
      },
];
function initData(){
    let str = "";
    // 利用foreach跑初始資料
    data.forEach(function (item) {
      str += `<li>${item.content}<input class="delete" type="button" value="刪除待辦"></li>`;
    });
    // 找到class = todo-list將li加在後面
    document.querySelector(".todo-list").innerHTML = str;
}
initData();
```

效果:

![](https://i.imgur.com/q2W4lAC.jpg)

## 新增待辦事項

`index.js`更新如下

```javascript=
const txt = document.querySelector(".txt");
const create = document.querySelector(".create");
let data = [];
function initData() {
  let str = "";
  data.forEach(function (item) {
    str += `<li>${item.content}<input class="delete" type="button" value="刪除待辦"></li>`;
  });

  document.querySelector(".todo-list").innerHTML = str;
}

create.addEventListener("click", function (e) {
    // 防呆
    if (txt.value === "") {
    alert("請輸入待辦事項");
    return;
    }
    // 增加進去data的array
    data.push({ content: txt.value });
    // 重新呼叫
    initData();
});
```

效果:
![](https://i.imgur.com/V07n6rW.jpg)

## 刪除待辦事項

`index.js`更新如下

```javascript=
const txt = document.querySelector(".txt");
const create = document.querySelector(".create");
const list = document.querySelector(".todo-list");
let data = [];
function initData() {
  let str = "";
  data.forEach(function (item, index) {
      // 利用取得index知道該刪除哪一個li tag
    str += `<li>${item.content}<input class="delete" type="button" data-num=${index} value="刪除待辦"></li>`;
  });

  document.querySelector(".todo-list").innerHTML = str;
}
// 新增待辦監聽
create.addEventListener("click", function (e) {
  if (txt.value === "") {
    alert("請輸入待辦事項");
    return;
  }
  data.push({ content: txt.value });
  txt.value = ""; // 點擊輸入後，清空輸入框
  initData();
});
// 刪除待辦監聽
list.addEventListener("click", function (e) {
  if (e.target.className === "delete") {
    data.splice(e.target.dataset.num, 1);
    initData();
  }
});
```

## codepen

<iframe height="300" style="width: 100%;" scrolling="no" title="Untitled" src="https://codepen.io/joe94113/embed/xxXXVxq?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true">
  See the Pen <a href="https://codepen.io/joe94113/pen/xxXXVxq">
  Untitled</a> by 王冠智 (<a href="https://codepen.io/joe94113">@joe94113</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe>

這邊順便推薦一個css 選擇器的小遊戲
[Css Diner](https://flukeout.github.io/, https://i.imgur.com/mkn3r71.jpg)