JSFiddle - React, Tailwind, and code Playground

by evon0306

HTML

<input type="text">
<button onclick="add()">新增</button>
<select>
   <option value="normal">一般</option>
   <option value="important">重要</option>
   <option value="urgent">緊急</option>
</select>
<div id="root">
</div>

CSS

* {
  margin: 0;
  padding: 0;
  list-style: none;
}

JavaScript

var todos = [
   {
      title: "倒垃圾",
      category: "normal"
   },
   {
      title: "繳電話費",
      category: "important"
   },
   {
      title: "採買本週食材",
      category: "urgent"
   },
];

render();

function render(){
   const root = document.querySelector('#root');
   root.textContent = "";

   let ul = document.createElement('ul');
   for( let x in todos){
      let todo = todos[x];
      console.log(todo.category);
      let li = document.createElement('li');
      let span = document.createElement('span');
      let delBtn = document.createElement('button');
      delBtn.onclick = () => {
         console.log(x);
         todos.splice(x, 1)
         render();
      };

      if(todo.category == "urgent"){
         span.style.color = "red"
      }else if(todo.category == "important"){
         span.style.color = "blue"
      }else{
         span.style.color = "black"
      }

      span.textContent = todo.title;
      delBtn.textContent = "刪除";
      li.append(span);
      li.append(delBtn);
      ul.append(li);
   }
      root.append(ul);
}

function add(){
   let input = document.querySelector('input');
   let select = document.querySelector('select');
   let text = input.value;
   let change = select.value;
   todos.push({
      title: text,
      category: change
   });
   render();
   input.value = "";
   select.value = "normal";
}