← 第 2 关 – 魔法师

第 2/8 课 ⏱ 25 分钟

第一个法术:会做事的按钮

页面第一次对点击有反应。你会学会找到元素并监听事件。

跟我看:每个法术的三个步骤

JavaScript 在页面上做的大部分事都遵循三步:

  1. 找到页面上的元素(按钮、标题、图片……),
  2. 监听事件(点击、鼠标悬停、输入文字……),
  3. 做点什么(改文字、颜色、隐藏、显示……)。

代码里是这样。在 HTML 里加按钮和段落:

<button id="my-button">Click me</button>
<p id="greeting">Nothing has happened yet.</p>

script.js 里:

// 1. Find the elements by their id
const myButton = document.getElementById("my-button");
const greeting = document.getElementById("greeting");

// 2. Listen for a click on the button
myButton.addEventListener("click", () => {
  // 3. Do something: change the paragraph's text
  greeting.textContent = "The spell works! 🎉";
});

新东西拆解一下:

轮到你了 💪

给网站加上第一个法术。按项目选一个(或自己发明):

🏫 学校网站——"今天午餐吃什么?"按钮

HTML(首页):

<button id="lunch-button">What's for lunch today?</button>
<p id="lunch"></p>

script.js:

const lunchButton = document.getElementById("lunch-button");
const lunch = document.getElementById("lunch");

lunchButton.addEventListener("click", () => {
  lunch.textContent = "Today: pizza and salad! 🍕";
});
🙋 个人网站——"讲个笑话"按钮
<button id="joke-button">Tell me a joke</button>
<p id="joke"></p>
const jokeButton = document.getElementById("joke-button");
const joke = document.getElementById("joke");

jokeButton.addEventListener("click", () => {
  joke.textContent = "Why do programmers prefer dark mode? Because light attracts bugs! 😄";
});
🌍 旅行日记——"下次去哪?"按钮
<button id="where-button">Where are we going next?</button>
<p id="where"></p>
const whereButton = document.getElementById("where-button");
const where = document.getElementById("where");

whereButton.addEventListener("click", () => {
  where.textContent = "Packing our bags: we're headed to the beach in Greece! 🌊";
});
⚽ 俱乐部网站——"下场比赛什么时候?"按钮
<button id="match-button">When's the next match?</button>
<p id="match"></p>
const matchButton = document.getElementById("match-button");
const match = document.getElementById("match");

matchButton.addEventListener("click", () => {
  match.textContent = "Saturday at 10:00, home game vs. Riverside. Come cheer us on! 📣";
});

额外:用 CSS 给按钮加样式,让它好看:

button {
  font-size: 16px;
  font-weight: bold;
  padding: 10px 20px;
  border: none;
  border-radius: 999px;
  background-color: #1d4ed8;
  color: white;
  cursor: pointer;
}

button:hover {
  background-color: #1e40af;
}
⚠️

不工作? 打开控制台(F12)。最常见错误:1)HTML 的 idgetElementById 里的名字不完全一样(大小写也算),2)<script> 不在 <body> 最末尾,3)缺括号——控制台会告诉你行号。

检查一下: 你点按钮,页面上出现文字。你刚刚连接了网页三种语言:HTML(按钮)、CSS(外观)、JavaScript(行为)。

这堂课你要记住