ICT Elective B · Chapter 5 資訊及通訊科技 選修B · 第五章

Introduction to Client-Side Scripting 客戶端腳本簡介

Master JavaScript fundamentals, DOM manipulation, events, and interactive web application development. 掌握JavaScript基礎知識、DOM操作、事件處理,以及互動式網頁應用程式開發。

6 Core Topics 6個核心主題
15 Quiz Questions 15道測驗題
24 Flashcards 24張閃卡
Past Exam Questions 歷屆試題

Chapter Overview 章節概覽

Navigate to any section of this interactive study guide. 點擊任意卡片跳轉至對應學習章節。

5.0
Core Concepts核心概念
5.1
JS BasicsJavaScript基礎
5.2
Control Structures控制結構
5.3
DOM ManipulationDOM操作
5.4
Events & Handlers事件與處理
Quiz互動測驗
Flashcards閃卡練習
Past Questions歷屆試題

What is Client-Side Scripting? 甚麼是客戶端腳本?

Understanding the role of JavaScript in modern web development. 了解JavaScript在現代網頁開發中的角色。

Client-Side Scripting客戶端腳本

Code (JavaScript) that runs in the user's browser, not on the server. It enables dynamic, interactive web pages without server round-trips. 在用戶瀏覽器中執行的程式碼(JavaScript),而非在伺服器上執行。它使網頁無需向伺服器發送請求即可實現動態互動效果。

JavaScriptJavaScript

The primary client-side scripting language for the web. JavaScript adds interactivity to HTML pages and can manipulate page content dynamically. 網頁最主要的客戶端腳本語言。JavaScript為HTML頁面添加互動性,並能動態操控頁面內容。

DOM (Document Object Model)文件物件模型 (DOM)

An API that represents the HTML document as a tree of objects. JavaScript uses the DOM to read and modify page content, structure, and style. 將HTML文件表示為物件樹的API。JavaScript使用DOM來讀取和修改頁面內容、結構和樣式。

Event-Driven Programming事件驅動程式設計

A programming paradigm where code execution is triggered by events (user clicks, key presses, page loads), making web apps interactive. 一種程式設計範式,程式碼的執行由事件(用戶點擊、按鍵、頁面載入)觸發,使網頁應用程式具有互動性。

Developer Mode (F12)開發者模式 (F12)

Browser tools accessed with F12 key. Includes Elements tab (HTML/CSS), Console (JavaScript output/errors), Network (HTTP requests). 按F12鍵訪問的瀏覽器工具。包含Elements標籤(HTML/CSS)、Console(JavaScript輸出/錯誤)、Network(HTTP請求)。

Learning Objectives學習目標

Describe client-side scripting · Understand JS constructs & data types · Implement control structures · Manipulate DOM · Use events & handlers 描述客戶端腳本的用途 · 理解JS構造及數據類型 · 實現控制結構 · 操控DOM · 使用事件與事件處理器

Client-Side vs Server-Side客戶端 vs 伺服器端 Client-side code (JavaScript) runs in the browser — changes are instant and don't require a server request. Server-side code (PHP, Python) runs on the web server and sends back HTML responses. 客戶端程式碼(JavaScript)在瀏覽器中執行——更改即時生效,無需向伺服器發送請求。伺服器端程式碼(PHP、Python)在網頁伺服器上執行並返回HTML回應。

Variables, Data Types & Operators 變數、數據類型與運算符

A. Variables — Declaring with let A. 變數 — 使用 let 宣告

In JavaScript, variables are declared using the let keyword. A variable stores a value that can be read and changed later.

在JavaScript中,變數使用 let 關鍵字宣告。變數儲存一個可以稍後讀取和修改的值。

let name = "Hollis"; // String variable / 字串變數 let age = 17; // Number variable / 數值變數 let passed = true; // Boolean variable / 布林變數 console.log(name); // Output: Hollis
B. Data Types B. 數據類型
Data Type數據類型 Example例子 Notes備注
Number 0.0, 1.0, 2.5, -300.1 All numbers are floating-point (no separate Integer type)所有數值均為浮點數(沒有獨立的整數類型)
Boolean true, false Must be lowercase; don't use quotes必須小寫;不要加引號
String "Hello World" A series of characters enclosed in double quotes用雙引號括起來的字符序列
C. Arithmetic & Assignment Operators C. 算術與賦值運算符

Arithmetic Operators算術運算符

10 + 3 // 13 (Addition) 10 - 3 // 7 (Subtraction) 10 * 3 // 30 (Multiplication) 10 / 3 // 3.33... (Division) 10 % 3 // 1 (Modulus 餘數) 10 ** 3 // 1000 (Exponent 次方)

Shorthand Assignment簡寫賦值

let x = 10; x += 5; // x = x + 5 → 15 x -= 3; // x = x - 3 → 12 x *= 2; // x = x * 2 → 24 x /= 4; // x = x / 4 → 6 x++; // x = x + 1 → 7 x--; // x = x - 1 → 6
D. String Manipulation D. 字串操作

String Concatenation (+): Combines strings together.

字串連接(+):將字串合併在一起。

let a = "Hello"; let b = "World"; console.log(a + " " + b); // >> Hello World

Template Literal: Insert variables into strings using backticks and ${}.

模板字面量:使用反引號和 ${} 將變數插入字串中。

let name = "Nicholas"; let msg = `${name} will do a great job`; console.log(msg); // >> Nicholas will do a great job
Template literals ONLY work with backticks (`). Single quotes and double quotes will NOT work! 模板字面量只能使用反引號(`)。單引號和雙引號不起作用!
E. Arrays E. 陣列
// Create an array / 建立陣列 let staff = []; let members = ["Thomas", "Sandra"]; // Add element / 新增元素 members.push("Kelvin"); // Access element (0-indexed) / 存取元素(從0開始) console.log(members[0]); // >> Thomas console.log(members[1]); // >> Sandra // Check length / 檢查長度 let count = members.length; // 3

Boolean Expressions, Selection & Loops 布林表達式、選擇與循環

A. Relational & Logical Operators A. 關係運算符與邏輯運算符

Relational Operators關係運算符

Operator運算符Meaning含義
==Equal等於
!=Not equal不等於
<Less than小於
>Greater than大於
<=Less than or equal小於或等於
>=Greater than or equal大於或等於

Logical Operators邏輯運算符

Operation運算Operator運算符
AND&&
OR||
NOT!
B. Selection — if...else B. 選擇結構 — if...else

if...elseif...else

let player = 25; if (player > 30) { console.log("Game start"); } else { console.log("Not enough player"); } // >> Not enough player

if...else if...elseif...else if...else

let age = 15; if (age > 16) { console.log("Grade A"); } else if (age > 14) { console.log("Grade B"); } else { console.log("Grade C"); } // >> Grade B
C. Loops — while & for C. 循環 — while 與 for

while loopwhile 循環

let num = 17; while (num < 100) { console.log(num); num += 17; } // >> 17, 34, 51, 68, 85

for loopfor 循環

for (let i = 0; i < 5; i++) { console.log(i); } // >> 0, 1, 2, 3, 4 // Loop through array / 遍歷陣列 let scores = [80, 90, 75]; for (let i = 0; i < scores.length; i++) { console.log(scores[i]); }

Manipulating HTML Elements with JavaScript 使用JavaScript操控HTML元素

A. The id Attribute A. id 屬性

The id attribute uniquely identifies an HTML element within a page. It is used by JavaScript to select a specific element for manipulation.

id 屬性在頁面中唯一標識一個HTML元素。JavaScript用它來選取特定元素進行操作。

<!-- HTML --> <h1 id="title">Personal Info</h1> <p id="name">My name is ...</p> <button id="btn">Click me</button>
Each id must be unique within the same HTML document. Multiple elements can exist without an id, but if they have one, it must not be repeated. 每個 id 在同一HTML文件中必須唯一。元素可以沒有 id,但如果有,則不能重複。
B. document.getElementById() & innerText B. document.getElementById() 與 innerText
  • 1
    Select the element選取元素 Use document.getElementById("id") to select the HTML element with the specified id. 使用 document.getElementById("id") 選取指定id的HTML元素。
  • 2
    Change the text更改文字 Assign a new string to the .innerText property to change the displayed text. 將新字串賦值給 .innerText 屬性以更改顯示的文字。
// Change text in <p id="name"> / 更改 <p id="name"> 的文字 document.getElementById("name").innerText = "Hollis Leung"; // Retrieve text / 讀取文字 let currentText = document.getElementById("name").innerText;
C. innerText vs innerHTML C. innerText 與 innerHTML 的比較

innerText

Changes only the plain text content. HTML tags in the string are treated as literal text, not parsed as HTML. 只更改純文字內容。字串中的HTML標籤被視為純文字,不會被解析為HTML。

element.innerText = "Hello <b>World</b>"; // Shows: Hello <b>World</b>

innerHTML

Changes the HTML markup inside the element. HTML tags in the string ARE parsed and rendered by the browser. 更改元素內的HTML標記。字串中的HTML標籤會被瀏覽器解析和渲染。

element.innerHTML = "Hello <b>World</b>"; // Shows: Hello World
Tip: Use innerText for plain text changes. Use innerHTML when you need HTML formatting (bold, links, etc.). 提示:純文字更改使用 innerText。需要HTML格式(粗體、連結等)時使用 innerHTML。
D. Counter Application Example D. 計數器應用程式範例

This example shows how to retrieve text from an element, convert it to a number, and write it back.

此範例展示如何從元素讀取文字、轉換為數字,再寫回元素。

<html> <head> <script> function increment() { let x = document.getElementById("counter").innerText; x = Number(x) + 1; // Convert string to number / 字串轉數字 document.getElementById("counter").innerText = x; } function decrement() { let x = document.getElementById("counter").innerText; x = Number(x) - 1; document.getElementById("counter").innerText = x; } </script> </head> <body> <h1>Counter</h1> <p id="counter">0</p> <button onclick="increment()">Add</button> <button onclick="decrement()">Subtract</button> </body> </html>
innerText always returns a string. Use Number() to convert it to a number before doing arithmetic. innerText 總是返回字串。在進行算術運算之前,需要使用 Number() 將其轉換為數字。

Functions, Events & Event Handlers 函數、事件與事件處理器

A. Defining Functions A. 定義函數

A function groups reusable code under a name. It is defined once and can be called (invoked) multiple times.

函數將可重用的程式碼歸納在一個名稱下。它只需定義一次,可以被多次調用(執行)。

// Define a function / 定義函數 function showName() { document.getElementById("name").innerText = "Hollis Leung"; } // Function with parameters / 帶參數的函數 function greet(personName) { document.getElementById("msg").innerText = "Hello, " + personName; } // Call (invoke) the function / 調用函數 showName(); greet("Alice");
B. Common Events B. 常見事件
Event事件 Element元素 Description描述
click <button> User clicked the button用戶點擊了按鈕
change <input type="text"> Text in input field has changed輸入框中的文字已更改
copy <p> User copied text from the paragraph用戶從段落中複製了文字
focus <input type="password"> User focused on the password field用戶聚焦於密碼欄
submit <form> HTML form is being submittedHTML表單正在提交
C. Registering Event Handlers C. 註冊事件處理器

An event handler is a function that runs when an event occurs. Register it by assigning the function to an event attribute (e.g., onclick).

事件處理器是事件發生時執行的函數。通過將函數賦值給事件屬性(如 onclick)來註冊它。

<html> <head> <script> function showName() { document.getElementById("name").innerText = "Hollis Leung"; } </script> </head> <body> <p id="name">My name is ...</p> <!-- onclick registers showName() as the click event handler --> <button type="button" onclick="showName()">Click me</button> </body> </html>
Functions should be defined in the <head> section so they are available before the page body loads. The onclick attribute links the button's click event to the function. 函數應在 <head> 部分定義,以便在頁面主體載入之前可用。onclick 屬性將按鈕的點擊事件連結到函數。
D. Client-Side Form Validation D. 客戶端表單驗證

The submit event on a form can be used to validate user input before sending data to the server. This prevents invalid data from being sent.

表單的 submit 事件可用於在將數據發送到伺服器之前驗證用戶輸入。這可以防止無效數據被發送。

// Example: Validate birthday guess / 範例:驗證生日猜測 function checkBirthday() { let month = document.getElementById("month").value; let day = document.getElementById("day").value; if (month == "4" && day == "19") { document.getElementById("result").innerText = "Hooray! You must know me very well"; } else if (month == "4") { document.getElementById("result").innerText = "Got the month right but not the day!"; } else { document.getElementById("result").innerText = "Your guess was incorrect, try again!"; } }

Test Your Knowledge 測試你的知識

15 questions covering all topics in Chapter 5. Select an answer and submit to see your score. 涵蓋第五章所有主題的15道題目。選擇答案後提交以查看你的得分。

1. Which keyword is used to declare a variable in JavaScript? 1. 在JavaScript中,哪個關鍵字用於宣告變數?
Avarvar
Bletlet
Cintint
Ddefinedefine
Answer: B — let. In modern JavaScript, let is the standard keyword for declaring variables. It allows reassignment but is block-scoped. 答案:B — let。在現代JavaScript中,let 是宣告變數的標準關鍵字。它允許重新賦值,但有塊作用域。
2. What does document.getElementById("name").innerText = "Alice" do? 2. document.getElementById("name").innerText = "Alice" 的作用是什麼?
ACreates a new HTML element with id "name"建立一個id為"name"的新HTML元素
BChanges the text content of the element with id "name" to "Alice"將id為"name"的元素的文字內容更改為"Alice"
CDeletes the element with id "name"刪除id為"name"的元素
DReads the text content of the element with id "name"讀取id為"name"的元素的文字內容
Answer: B. document.getElementById() selects the element, and assigning to .innerText changes its displayed text content. 答案:B。document.getElementById() 選取元素,賦值給 .innerText 更改其顯示的文字內容。
3. What is the output of: let x = 5; x += 3; console.log(x); 3. 以下程式碼的輸出是什麼:let x = 5; x += 3; console.log(x);
A5
B3
C8
D53
Answer: C — 8. x += 3 is shorthand for x = x + 3, so 5 + 3 = 8. 答案:C — 8。x += 3 是 x = x + 3 的簡寫,所以 5 + 3 = 8。
4. Which of the following is the correct way to use a template literal in JavaScript? 4. 以下哪個是在JavaScript中正確使用模板字面量的方式?
A"Hello ${name}"
B'Hello ${name}'
C`Hello ${name}`
D"Hello " + {name}
Answer: C. Template literals MUST use backticks (`). Single and double quotes do not support ${} variable interpolation. 答案:C。模板字面量必須使用反引號(`)。單引號和雙引號不支持 ${} 變數插值。
5. What is the difference between innerText and innerHTML? 5. innerText 和 innerHTML 有什麼區別?
AThey are identical in functionality它們的功能完全相同
BinnerText sets plain text; innerHTML parses HTML tags in the stringinnerText設置純文字;innerHTML解析字串中的HTML標籤
CinnerHTML sets plain text; innerText parses HTML tagsinnerHTML設置純文字;innerText解析HTML標籤
DinnerText is for <div> only; innerHTML is for <p> onlyinnerText只用於<div>;innerHTML只用於<p>
Answer: B. innerText treats the string as plain text (HTML tags shown literally). innerHTML parses HTML tags and renders them. 答案:B。innerText 將字串視為純文字(HTML標籤按字面顯示)。innerHTML 解析HTML標籤並渲染它們。
6. What will let a = [10, 20, 30]; console.log(a[1]); output? 6. let a = [10, 20, 30]; console.log(a[1]); 的輸出是什麼?
A10
B20
C30
D3
Answer: B — 20. Arrays are 0-indexed. Index 0 = 10, index 1 = 20, index 2 = 30. 答案:B — 20。陣列從索引0開始。索引0 = 10,索引1 = 20,索引2 = 30。
7. Which attribute is used to register a click event handler on a button in HTML? 7. 在HTML中,哪個屬性用於在按鈕上註冊點擊事件處理器?
Aonpress
Bonclick
Consubmit
Donchange
Answer: B — onclick. The onclick attribute registers a function as the handler for the click event on an HTML element. 答案:B — onclick。onclick 屬性將函數註冊為HTML元素點擊事件的處理器。
8. What is the correct Boolean data type value in JavaScript? 8. JavaScript中正確的布林數據類型值是什麼?
ATrue
BTRUE
Ctrue
D"true"
Answer: C — true. JavaScript Boolean values must be lowercase: true or false. Using quotes makes it a string, not a Boolean. 答案:C — true。JavaScript布林值必須小寫:true 或 false。使用引號會使其成為字串,而非布林值。
9. What does the Number() function do? 9. Number() 函數的作用是什麼?
ACreates a new number variable建立一個新的數值變數
BConverts a value (e.g., string) to a number data type將一個值(例如字串)轉換為數值數據類型
CRounds a number to the nearest integer將數字四捨五入到最近的整數
DChecks if a value is a number檢查一個值是否為數字
Answer: B. Number() converts a value (typically a string retrieved from innerText) to a numeric type so arithmetic can be performed. 答案:B。Number() 將一個值(通常是從 innerText 獲取的字串)轉換為數值類型,以便進行算術運算。
10. What is the output of: let x = 10; while (x < 30) { x += 10; } console.log(x); 10. 以下程式碼的輸出是什麼:let x = 10; while (x < 30) { x += 10; } console.log(x);
A20
B30
C40
D10
Answer: B — 30. x starts at 10. Loop: 10 < 30 → x = 20; 20 < 30 → x = 30; 30 is NOT < 30, loop ends. Output: 30. 答案:B — 30。x從10開始。循環:10 < 30 → x = 20;20 < 30 → x = 30;30 不小於 30,循環結束。輸出:30。
11. Which logical operator represents AND in JavaScript? 11. 在JavaScript中,哪個邏輯運算符代表AND(與)?
A&
BAND
C&&
Dand
Answer: C — &&. JavaScript uses && for AND, || for OR, and ! for NOT. 答案:C — &&。JavaScript使用 && 表示AND,|| 表示OR,! 表示NOT。
12. Where should JavaScript functions typically be defined in an HTML file? 12. JavaScript函數通常應在HTML文件的哪個部分定義?
AInside the <body> tag, after all content在 <body> 標籤內,所有內容之後
BInside the <head> tag, within <script> tags在 <head> 標籤內,<script> 標籤中
CIn a separate CSS file在單獨的CSS文件中
DInside the <footer> tag在 <footer> 標籤內
Answer: B. Functions should be in <head><script>...</script></head> so they are loaded and available before the page body renders. 答案:B。函數應放在 <head><script>...</script></head> 中,這樣在頁面主體渲染之前它們就已載入並可用。
13. What does members.push("Kelvin") do to an array? 13. members.push("Kelvin") 對陣列做了什麼?
ARemoves the last element from the array從陣列中移除最後一個元素
BAdds "Kelvin" to the beginning of the array將"Kelvin"添加到陣列的開頭
CAdds "Kelvin" to the end of the array將"Kelvin"添加到陣列的末尾
DSearches for "Kelvin" in the array在陣列中搜索"Kelvin"
Answer: C. The push() method adds a new element to the END of an array and returns the new length. 答案:C。push() 方法將新元素添加到陣列的末尾,並返回新的長度。
14. JavaScript code runs on the ___. 14. JavaScript程式碼在___上執行。
AWeb server網頁伺服器
BDatabase server數據庫伺服器
CClient's browser客戶端的瀏覽器
DCloud computing platform雲計算平台
Answer: C — Client's browser. This is what makes JavaScript "client-side" — it executes in the user's browser, not on the server. 答案:C — 客戶端的瀏覽器。這就是JavaScript被稱為"客戶端"的原因——它在用戶的瀏覽器中執行,而不是在伺服器上。
15. What is the result of 10 % 3 in JavaScript? 15. JavaScript中 10 % 3 的結果是什麼?
A3
B3.33
C0
D1
Answer: D — 1. The % (modulus) operator returns the remainder of division. 10 ÷ 3 = 3 remainder 1. 答案:D — 1。%(餘數)運算符返回除法的餘數。10 ÷ 3 = 3 餘 1。

Key Terms & Concepts 關鍵術語與概念

Click each card to flip and reveal the definition. 24 cards covering all Chapter 5 vocabulary. 點擊每張卡片翻轉以查看定義。24張卡片涵蓋第五章所有詞彙。

Exam Practice Questions 考試練習題

Practice questions modelled on DSE and school examination formats. Click "View Reference Answer" to see the model answer. 參考DSE及學校考試格式的練習題。點擊「查看參考答案」查看參考答案。

8
Total Questions題目總數
3
Easy基礎
3
Medium中等
2
Hard困難
Q1 Easy基礎 Multiple Choice
Which of the following correctly declares a variable named score and assigns it the value 100 in JavaScript? 以下哪個選項正確地在JavaScript中宣告了一個名為 score 的變數並賦值為100?

A. int score = 100;
B. let score = 100;
C. var score == 100;
D. score := 100;
Answer: B答案:B
let score = 100; is the correct modern JavaScript syntax. int is a PHP/Java keyword, not used in JavaScript. == is a comparison operator, not assignment. := is not valid JavaScript syntax. let score = 100; 是正確的現代JavaScript語法。int 是PHP/Java的關鍵字,JavaScript中不使用。== 是比較運算符,不是賦值運算符。:= 不是有效的JavaScript語法。
Q2 Easy基礎 Short Answer
State ONE difference between innerText and innerHTML when used to modify an HTML element's content. 說明在修改HTML元素內容時,innerText 和 innerHTML 之間的一個區別。

[2 marks / 2分]
Reference Answer:參考答案:
innerText sets the plain text content of an element — any HTML tags in the assigned string are displayed as literal text characters (1 mark). innerHTML sets the HTML markup content — HTML tags in the string are parsed and rendered by the browser, allowing formatting changes (1 mark). innerText 設置元素的純文字內容——賦值字串中的HTML標籤以字面文字字符顯示(1分)。innerHTML 設置HTML標記內容——字串中的HTML標籤由瀏覽器解析和渲染,允許格式更改(1分)。
Q3 Easy基礎 Short Answer
Explain what the id attribute is used for in HTML and why it is important when using JavaScript to manipulate web pages. 解釋HTML中 id 屬性的用途,以及在使用JavaScript操控網頁時它為何重要。

[2 marks / 2分]
Reference Answer:參考答案:
The id attribute is a unique identifier for an HTML element within a web page (1 mark). It is important because JavaScript uses document.getElementById() to select a specific element for manipulation — without a unique id, it would not be possible to target a specific element (1 mark). id 屬性是網頁中HTML元素的唯一標識符(1分)。它很重要,因為JavaScript使用 document.getElementById() 來選取特定元素進行操作——沒有唯一的id,就無法針對特定元素(1分)。
Q4 Medium中等 Code Completion
Complete the JavaScript function below. The function should check if a student's score (stored in <p id="score">) is 50 or above. If yes, display "Pass" in <p id="result">; otherwise display "Fail". 完成以下JavaScript函數。該函數應檢查學生的分數(儲存在 <p id="score"> 中)是否達到50分或以上。如果是,在 <p id="result"> 中顯示"Pass";否則顯示"Fail"。

function checkResult() { let s = document.getElementById("score").innerText; let score = Number(s); // Complete the code here... / 在此處完成程式碼... ___________________________ ___________________________ ___________________________ ___________________________ }
[4 marks / 4分]
Reference Answer:參考答案:
function checkResult() { let s = document.getElementById("score").innerText; let score = Number(s); if (score >= 50) { // 1 mark document.getElementById("result") .innerText = "Pass"; // 1 mark } else { // 1 mark document.getElementById("result") .innerText = "Fail"; // 1 mark } }
Key points: correct comparison operator (>=), correct use of getElementById and innerText for output. 關鍵點:正確的比較運算符(>=),正確使用 getElementById 和 innerText 進行輸出。
Q5 Medium中等 Code Writing
Write a JavaScript function countEven(arr) that takes an array of numbers and returns the count of even numbers in the array. (Hint: A number is even if number % 2 == 0) 編寫一個JavaScript函數 countEven(arr),接受一個數字陣列並返回陣列中偶數的個數。(提示:如果 number % 2 == 0,則該數字為偶數)

[4 marks / 4分]
Reference Answer:參考答案:
function countEven(arr) { let count = 0; // 1 mark: initialise counter for (let i = 0; i < arr.length; i++) { // 1 mark: correct loop if (arr[i] % 2 == 0) { // 1 mark: correct condition count++; // 1 mark: increment counter } } return count; }
Q6 Medium中等 Explanation
Explain the concept of an "event" and an "event handler" in JavaScript. Give ONE example of each and describe how they work together in a web application. 解釋JavaScript中「事件」和「事件處理器」的概念。各舉一個例子,並描述它們如何在網頁應用程式中協同工作。

[4 marks / 4分]
Reference Answer:參考答案:
An event is an action that occurs in a web application, triggered by the user or the browser (e.g., a user clicking a button — the click event) (1 mark + 1 mark for example). An event handler is a JavaScript function that is registered to execute when a specific event occurs (1 mark). They work together by registering the function as a handler using an event attribute — e.g., onclick="myFunction()" on a button means myFunction() runs whenever the button is clicked (1 mark). 事件是在網頁應用程式中發生的動作,由用戶或瀏覽器觸發(例如,用戶點擊按鈕——click 事件)(1分 + 例子1分)。事件處理器是當特定事件發生時被註冊執行的JavaScript函數(1分)。它們通過使用事件屬性將函數註冊為處理器來協同工作——例如,按鈕上的 onclick="myFunction()" 表示每次點擊按鈕時 myFunction() 都會執行(1分)。
Q7 Hard困難 Extended Code Writing
Hollis is building a quiz application. Write the complete JavaScript and HTML for a function that: (a) reads the user's answer from <input id="answer">, (b) compares it to the correct answer "JavaScript", (c) displays "Correct!" or "Wrong! The answer is JavaScript" in <p id="feedback">, and (d) includes a button that triggers this function. Hollis正在開發一個測驗應用程式。編寫完整的JavaScript和HTML,實現以下功能:(a) 從 <input id="answer"> 讀取用戶答案,(b) 與正確答案"JavaScript"進行比較,(c) 在 <p id="feedback"> 中顯示"Correct!"或"Wrong! The answer is JavaScript",(d) 包含觸發此函數的按鈕。

[6 marks / 6分]
Reference Answer:參考答案:
<html> <head> <script> function checkAnswer() { // 1 mark: function defined let userAns = document .getElementById("answer").value; // 1 mark: read .value if (userAns == "JavaScript") { // 1 mark: correct comparison document.getElementById("feedback") .innerText = "Correct!"; // 1 mark } else { document.getElementById("feedback") .innerText = "Wrong! The answer is JavaScript"; // 1 mark } } </script> </head> <body> <input type="text" id="answer"> <button onclick="checkAnswer()">Submit</button> // 1 mark <p id="feedback"></p> </body> </html>
Note: Use .value (not .innerText) to read from <input> elements. 注意:讀取 <input> 元素時使用 .value(而非 .innerText)。
Q8 Hard困難 Analysis & Code
Consider the following code. Identify and explain TWO errors, then write the corrected version. 考慮以下程式碼。找出並解釋兩個錯誤,然後寫出更正後的版本。

let scores = [80, 70, 90]; let total = 0; for (let i = 1; i <= scores.length; i++) { total = total + scores[i]; } console.log("Total: " + total);
[6 marks / 6分]
Reference Answer — Two Errors:參考答案 — 兩個錯誤:

Error 1: Loop starts at i = 1 instead of i = 0. Arrays are 0-indexed, so the first element (80) is skipped (2 marks).
Error 2: Loop condition is i <= scores.length instead of i < scores.length. When i = 3 (= length), scores[3] is undefined, causing incorrect total (2 marks).
錯誤1:循環從 i = 1 而不是 i = 0 開始。陣列從索引0開始,所以第一個元素(80)被跳過(2分)。
錯誤2:循環條件是 i <= scores.length 而不是 i < scores.length。當 i = 3(= 長度)時,scores[3] 是 undefined,導致總和不正確(2分)。


Corrected Code:更正後的程式碼:
let scores = [80, 70, 90]; let total = 0; for (let i = 0; i < scores.length; i++) { // Fixed: i=0, i<length total = total + scores[i]; } console.log("Total: " + total); // >> Total: 240
(2 marks for corrected code) (更正後的程式碼2分)