logo

JavaScript 事件处理

✏️ Editable
Loading...
Live Preview
+Enter Run+R Reset

About This Exercise

事件就是“用户做了什么”:点击按钮、输入内容、提交表单。

前端代码大部分不是一直跑,而是“等事件发生再执行”。

你将学到:

  • addEventListener 绑定监听
  • 处理 click / input / submit 三种常见事件
  • event.target 读取输入值
  • preventDefault 阻止表单默认行为
Beginner⏱ 25-30 min

Learning Objectives

  • 理解事件驱动编程的基本模型
  • 掌握 addEventListener 的基础写法
  • 能实现点击计数与实时输入同步
  • 能安全处理表单提交

Scenario

你在做一个交互演示页: 用户点击按钮时计数增加,输入文本时实时显示,提交表单时输出日志但不刷新页面。

Why Do This

  • Frontend JS is not just about knowing the syntax — the key is reliably manipulating the DOM and managing interaction state.
  • Break down the event flow (trigger -> handle -> update UI) before coding, and you will make significantly fewer errors.
  • Rule-based validation helps you develop a testable frontend mindset.

Hands-on Practice

  • Write out the event flow in comments first, then implement the functions.
  • Add an edge case branch for invalid input or empty data.
  • Explain why each validation rule is needed.

Common Mistakes

  • Only testing the happy path without verifying edge inputs or repeated clicks.
  • Mixing event binding and state updates together, making future maintenance difficult.
  • Console output looks correct but the UI is not actually updated.

Deliverable

A reusable interaction component scaffold (event flow description + key functions + edge case handling).

My Progress

Completed Steps0 / 3
Total Attempts0
Best Score0%

Completion Criteria (Checkable)

Confirm before completing this Lab

Reflection Questions (Recommended)

Describe the event flow of this Lab in 2-3 sentences (trigger -> handle -> update).

What edge case did you add? Why is it easy to miss?

How confident are you with this interaction pattern now?

Tags

JavaScriptEventsaddEventListenerInteraction