JavaScript
学习 JavaScript — programming language 的 web 那个制作 pages interactive.
你将学到
- 什么 JavaScript 是 and 为什么它 运行 in 浏览器
- 如何 JS interacts 使用 HTML 通过 DOM
- 如何事件处理函数 respond 到用户操作
- difference 之间 JavaScript and Java
概念讲解
JavaScript
JavaScript 是 the programming language of the web. Every modern browser has a built-in JavaScript engine, so JS code runs directly on the user's device without any installation. HTML gives a page structure; CSS gives it style; JavaScript gives it behavior.
Interactivity Through the DOM
The DOM (Document Object Model) is the browser's in-memory representation of your HTML. JavaScript can read and modify the DOM — change text, add elements, update styles — in response to user actions.
// Find an element and change its text
const heading = document.getElementById("title");
heading.textContent = "Welcome 后面!";
Event Handlers
An event is something that happens — a click, a keypress, a page load. You attach a handler — a function that runs when the event fires:
const button = document.querySelector("#myButton");
button.addEventListener("点击", () => {
alert("你点击 button!");
});
This is how every interactive web feature works: forms that validate, menus that open, data that loads without a page refresh.
JavaScript vs. Java
Despite the name, JavaScript and Java are completely different languages. JavaScript was named "JavaScript" as a marketing move in 1995 to ride on Java's popularity. They have different syntax, different runtimes, and different use cases. Do not confuse them.
Where JS Runs
- In the browser — manipulating the DOM, handling events, fetching data.
- On the server — via Node.js, handling files, databases, and APIs.
The same language, two environments. This is why JavaScript is called " one language 你能 use everywhere."
示例代码
// A counter that updates the DOM when a button is clicked
let count = 0;
const display = document.getElementById("count");
const button = document.getElementById("increment");
button.addEventListener("click", () => {
count++;
display.textContent = `Clicked ${count} times`;
// Change color based on count
if (count > 5) {
display.style.color = "red";
} else {
display.style.color = "black";
}
});
addEventListener listens for 点击. 每个点击 increments 计数器, 更新 DOM 文本, and conditionally 更改颜色. 这个是 模式后面大多数 interactive UI.
动手试一试
- Markdown Previewer
这个 tool 是构建使用 JavaScript — 它 reacts 到你的输入 in 真实时间, 只是如 interactive web apps.
常见错误
错误写法
Thinking JavaScript and Java 是 related.
正确做法
它们是 完全不同 languages. JavaScript 运行 in 浏览器 and 节点.js; Java 运行 on JVM. 相似 name 是 historical marketing accident.
错误写法
修改 DOM 之前它 有加载.
正确做法
Wrap DOM code in DOMContentLoaded, or 位置你的 <script> at 端的 <请求体>. 否则 document.getElementById 可能返回空 因为元素做 不 exist yet.
相关资源
相关代码片段
- JavaScript 数组方法
核心数组方法你 将 use constantly in web development.
相关速查表
- JavaScript Cheatsheet
完整引用 for 语法, DOM 方法, and 事件 handling.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。