ID (HTML)
一句话解释
id attribute gives HTML 元素 唯一 identifier on page, used for 样式, scripting, and anchoring.
用大白话说
id attribute assigns a unique name to a single HTML element on a page. No two elements on the same page should share the same id. This uniqueness makes ids useful for targeting one specific element — in CSS, JavaScript, or as a link anchor.
In CSS, an id is targeted with a hash: #请求头 { ... }. In JavaScript, document.getElementById('请求头') returns that exact element. In URLs, #小节-2 scrolls the page to the element with that id.
Because ids must be unique, they are not the right tool for reusable styles — use classes for that. Reserve ids for elements that appear once per page and need to be addressed individually, like a main header, a specific form, or a navigation bar.
示例
<header id="main-header">Welcome</header>
<style>
#main-header { background: #2563eb; color: white; }
</style>
<script>
const header = document.getElementById("main-header");
console.log(header.textContent); // "Welcome"
</script>id="主要-请求头" uniquely identifies this header. CSS targets it with #主要-请求头, JS with getElementById.
常见混淆
容易混淆的对象: 类
关键区别: id 是唯一每 page and targeted 使用
#id; 类能 是 shared 通过许多元素 and 是 targeted 使用.类. Use ids for one-的--kind 元素, 类 for repeated 样式.
相关术语
相关资源
相关课程
- HTML
id attribute 是 introduced 使用 HTML
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。