访问文档标题属性
在这一步中,你将学习如何使用 JavaScript 访问文档标题属性。我们将基于上一步创建的 HTML 文件,演示如何检索和操作文档的标题。
使用 WebIDE 在 ~/project
目录中创建一个名为 script.js
的新文件。添加以下 JavaScript 代码:
// Access the document title
console.log("Document Title:", document.title);
// Modify the document title
function changeTitle() {
document.title = "Updated DOM Properties Lab";
console.log("New Document Title:", document.title);
}
// Add a button to demonstrate title change
const button = document.createElement("button");
button.textContent = "Change Title";
button.onclick = changeTitle;
document.body.appendChild(button);
现在,更新 index.html
文件以包含 JavaScript 文件:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>DOM Properties Exploration</title>
</head>
<body>
<h1>Welcome to DOM Properties Lab</h1>
<p>This page will help us explore JavaScript DOM properties.</p>
<img src="https://example.com/sample-image.jpg" alt="Sample Image" />
<img src="https://example.com/another-image.jpg" alt="Another Image" />
<script src="script.js"></script>
</body>
</html>
当你在浏览器中打开此 HTML 文件时,你将看到以下行为:
浏览器控制台中的示例输出:
Document Title: DOM Properties Exploration
当你点击 "Change Title" 按钮时:
New Document Title: Updated DOM Properties Lab
演示的关键概念:
document.title
属性用于检索当前页面的标题
- 你可以使用 JavaScript 动态更改文档标题
- 标题显示在浏览器标签页中,并且可以在运行时修改