---
# System prepended metadata

title: to-do list
tags: [Javascript]

---

###### tags: `Javascript`

# to-do list

---

## 初始化
```javascript=
let data = [
  {
    "content":"代辦一"
  },
  {
    "content":"今天記得刷牙"
  },
  {
    "content":"今天記得尻尻"
  }
]

const list = document.querySelector(".list");
const txt = document.querySelector(".txt");
const save = document.querySelector(".save");

function renderData(){
  let str = '';
  data.forEach(function(item,index){
    str+=`
    <li>${item.content}<input type="button" 
    class="delete hi" data-num="${index}" value="刪除代辦"></li>
    `
  })
  const list = document.querySelector(".list");
  list.innerHTML = str;
}
```

## 新增
```javascript=
save.addEventListener('click',function(e){
  if(txt.value==""){
    alert("請輸入內容!");
    return;
  }
  let obj = {};
  obj.content = txt.value;
  console.log(obj);
  data.push(obj);
  renderData();
})
```

## 刪除
```javascript=
list.addEventListener('click',function(e){
  if(e.target.getAttribute("class") !== "delete "){
    alert("你沒有點擊到按鈕");
    return;
  }
  let num = e.target.getAttribute("data-num");
  data.splice(num,1);
  renderData();
})
```
