“Great web design without functionality is like a sports car with no engine.”
Paul Cookson
在進行開發之前,對要做什麼有個基本的概念和規劃是很重要的,先想一下一個計數器大概需要什麼:
有了規劃後,首先我們需要的就會是HTML創建這些元件(文字和按鈕),再來才會是用JavaScript跟這些元件進行互動:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Count: 0</h1>
<button>-1</button>
<button>Reset</button>
<button>+1</button>
</body>
</html>
接下來,為了讓JavaScript跟這些元件進行互動,我們需要給這些元件取名字(類似變數名稱),我們把這些元件都加上一個名字:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="count">Count: 0</h1>
<button id="decrement">-1</button>
<button id="reset">Reset</button>
<button id="increment">+1</button>
</body>
</html>
接下來嘗試用JavaScript進行互動:
<script>
function test()
{
alert("hi")
}
const decrementButton = document.getElementById('decrement');
decrementButton.addEventListener("click", test)
</script>
getElementById:根據傳入的ID回傳DOM元素(想像成元件)
addEventListener:當發生事件後,觸發函數。以這個例子是發生click點擊事件後,觸發test函數
點下後有彈出視窗就代表成功了!
接下來先讓我們先實現decrement的功能:
<script>
let count = 0;
function updateCount()
{
countDisplay.textContent = `Count: ${count}`;
}
function decrement()
{
count--;
updateCount();
}
const countDisplay = document.getElementById('count');
const decrementButton = document.getElementById('decrement');
decrementButton.addEventListener("click", decrement);
</script>
我們宣告的count變數,它不代表著畫面上看到的那個數字(文字元件),而是一個在內部偷偷統計的數字,這也是為什麼在decrement後要重新把數字元件的文字內容給更改成我們內部統計的數!
把reset和increment補完:
<script>
let count = 0;
function updateCount()
{
countDisplay.textContent = `Count: ${count}`;
}
function decrement()
{
count--;
updateCount();
}
function reset()
{
count = 0;
updateCount();
}
function increment()
{
count++;
updateCount();
}
const countDisplay = document.getElementById('count');
const decrementButton = document.getElementById('decrement');
const resetButton = document.getElementById('reset');
const incrementButton = document.getElementById('increment');
decrementButton.addEventListener("click", decrement);
resetButton.addEventListener("click", reset);
incrementButton.addEventListener("click", increment);
</script>
下一篇會補上一些優化和CSS!