跟我看:每个法术的三个步骤
JavaScript 在页面上做的大部分事都遵循三步:
- 找到页面上的元素(按钮、标题、图片……),
- 监听事件(点击、鼠标悬停、输入文字……),
- 做点什么(改文字、颜色、隐藏、显示……)。
代码里是这样。在 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! 🎉";
});
新东西拆解一下:
id="my-button"——元素的名字牌,类似 class,但id在页面上应该只出现一次。JavaScript 用它找元素。const——带名字的盒子(变量),存我们找到的元素。变量下次细说。document.getElementById("...")——“页面,给我找这个 id 的元素。”addEventListener("click", () => { ... })——“点击时,运行花括号里的东西。” 那个箭头() => {}叫函数——一段稍后运行的代码包。textContent——元素里的文字。赋新文字时,页面上马上变。
轮到你了 💪
给网站加上第一个法术。按项目选一个(或自己发明):
🏫 学校网站——"今天午餐吃什么?"按钮
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 的 id 和 getElementById 里的名字不完全一样(大小写也算),2)<script> 不在 <body> 最末尾,3)缺括号——控制台会告诉你行号。
✅
检查一下: 你点按钮,页面上出现文字。你刚刚连接了网页三种语言:HTML(按钮)、CSS(外观)、JavaScript(行为)。
这堂课你要记住
- 每个法术:找元素 → 监听事件 → 做某事。
document.getElementById("id")找元素,addEventListener("click", () => {...})等点击。textContent立刻改元素文字,不用刷新页面。
© 2026 Ing. Martin Polak / AlgoRhino · 内容使用条款