# 第二十九關:監聽切換排序功能

# 題目

禿頭俠又提到,客戶希望能夠針對 select 切換排序方式,還請依照以下 範例來設計。

PS:這次小杰發現今天的東西有點超出自己能力外,所以請 slack 的朋友,一起協助找資源,幫助他可以做出來,也請你將你找的資源文件加入到最下方:

<select>
  <option value="id">依照 id 編號排序(由1開始從上往下)</option>
  <option value="process">依照完課率排序(由最高到最低)</option>
</select>

// 以下為編號排序範例
<ul class="list">
  <li>編號 ID 1 為廖洧杰,他的完成進度為 5 %</li>
  <li>編號 ID 2 為王小明,他的完成進度為 33 %</li>
</ul>

// 以下為完課率排序範例
<ul class="list">
  <li>編號 ID 2 為王小明,他的完成進度為 33 %</li>
  <li>編號 ID 1 為廖洧杰,他的完成進度為 5 %</li>
</ul>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 文件資源

參考解答:

<div class="container mt-5">
	<select id="select" class="mb-5">
		<option value="id">依照 id 編號排序(由1開始從上往下)</option>
		<option value="process">依照完課率排序(由最高到最低)</option>
	</select>
	<table class="table table-striped">
		<thead class="thead-dark">
			<tr>
				<th scope="col">#</th>
				<th scope="col">Name</th>
				<th scope="col">完成率</th>
			</tr>
		</thead>
		<tbody class="userList">
		</tbody>
	</table>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const userList = document.querySelector(".userList");
const sortBtn = document.querySelector("#select");
const url =
  "https://raw.githubusercontent.com/hexschool/hexschoolNewbieJS/master/data.json";
let dataList = [];

axios
	.get(url)
	.then((res) => {
		dataList = res.data;
		render(dataList);
	})
	.catch((err) => {
		console.log(err);
	});

function sort() {
	if (this.value === "process") {
		dataList.sort((a, b) => parseInt(b.process) - parseInt(a.process));
	} else {
		dataList.sort((a, b) => a.id - b.id);
	}
	render(dataList);
}

function render(data) {
	let str = "";
	data.forEach((user) => {
		str += `
			<tr>
      	<th scope="row">${user.id}</th>
      	<td>${user.name}</td>
      	<td>${user.process}</td>
				</tr>`;
	});
	userList.innerHTML = str;
}

sortBtn.addEventListener("change", sort);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
最後更新: 7/23/2020, 1:25:46 AM