如何在 HTML 中为元素指定唯一的 ID?
htmlweb developmentfront end technology更新于 2025/4/10 4:28:17
对于每个 HTML 元素,id 属性指定一个特殊的 ID。id 属性的值在 HTML 内容中必须是唯一的。样式表中的特定样式声明使用 id 属性引用。JavaScript 也使用它来访问和修改具有给定 ID 的元素。
以下是示例……
示例
在下面的示例中,我们使用 <h1> 指向 ID 名称为"tutorial"。此 <h1> 将根据 #tutorial 进行样式设置。
<!DOCTYPE html> <html> <head> <style> #tutorial { background-color: lightblue; color: black; padding: 40px; text-align: center; } </style> </head> <body> <h1 id="tutorial">Welcome Everyone..</h1> </body> </html>
输出
执行上述脚本后,id 为"tutorial"的元素将根据 #tutorial 进行样式设置。
示例:使用 Javascript
Javascript 使用唯一 id 并操作具有指定 id 的元素。
<!DOCTYPE HTML> <html> <body> <h1 id="tutorial">Hello</h1> <button onclick="displayResult()">change text</button> <script> function displayResult() { document.getElementById("tutorial").innerHTML = "WELCOME"; } </script> </body> </html>
输出
首次尝试执行脚本时,它会显示文本"hello"。
点击更改文本按钮后,文本"hello"将更改为"welcome"。
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

