JavaScript 系列二:第7課 ── 用 Selector API 選取元素
by max002215
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<input type="text" placeholder="請輸入代辦事項" id="text1">
<select id="urgent" onchange="inputcolor()">
<option value="normal">普通</option>
<option value="important">重要</option>
<option value="emergent">緊急</option>
</select>
<button type="button"onclick="to_do_list()">新增</button>
<ul id="first_list">
<li>
<span>倒垃圾</span>
</li>
<li>
<span>繳電話費</span>
</li>
<li>
<span>採買本週食材</span>
</li>
</ul>
<button type="button" id="export_btn">匯出</button>
</body>
</html>
CSS
.important {
color: orange;
}
.emergent {
color: red;
}
.normal {
color: green;
}
.text_normal{
color:green;
font-weight: 500;
}
.text_important{
color:orange;
font-weight: 500;
}
.text_emergent{
color:red;
font-weight: 500;
}
JavaScript
function to_do_list() {
let list = document.querySelector("#text1").value;
let FirstList = document.querySelector("#first_list");
let listUrgent = document.querySelector("#urgent");
let list1 = document.createElement('li');
let list2 = document.createElement('span');
let btn1 = document.createElement('button');
let div1 = document.createElement('div');
let btn2 = document.createElement('button');
let listUrgentIndex = listUrgent.selectedIndex
let listUrgenValue = listUrgent.options[listUrgentIndex].value
let list3 = list2.textContent = list;
btn1.textContent = "刪除";
btn2.textContent = "已完成";
FirstList.append(list1);
list1.append(list2,div1, btn2, btn1);
btn1.onclick = hello;
div1.textContent = "(已完成)";
div1.style.display = "none"
btn2.onclick = Finish;
if (listUrgenValue == "normal") {
list2.className = list2.className + "normal";
} else if (listUrgenValue == "important") {
list2.className = list2.className + "important";
} else {
list2.className = list2.className + "emergent";
}
/* list2.append(list3);
*/
/* console.log(list) */
/* console.log(FirstList) */
/* console.log(list1) */
/* console.log(list2);
console.log(list3); */
function Finish() {
if (div1.style.display === "none") {
div1.style.display = "inline"
btn2.textContent = "標示未完成";
} else {
div1.style.display = "none"
btn2.textContent = "標示已完成";
}
}
}
let exportBtn = document.querySelector("#export_btn");
exportBtn.onclick = exportList;
function exportList() {
//先抓到主要清單子層
let list = document.querySelectorAll("#first_list li");
//設立空字串
let text = "";
//設立號碼
let num = 1;
//迴圈開始 item=迴圈變數名 of=把剛剛的抓到的子層陣列塞到迴圈變數裡面 list剛剛抓到子層的變數名
for (let item of list) {
let itemclass = item.querySelector("span").className;
let itemtext = item.querySelector("span").textContent
if (itemclass == "important") { //內容為空字串=空字串+號碼.轉成字串方法+點字串+迴圈變數.子層[陣列序號].文字內容+空字串
text = text +...