在HTML文档中,<title> 元素用于定义文档的标题,同时也是浏览器标签页上显示的标题。在HTML DOM 中,你可以使用 JavaScript 来访问和修改文档的标题,通过 document.title 属性。

以下是一个简单的例子,演示如何使用 JavaScript 和 HTML DOM 来获取和设置文档的标题:
<!DOCTYPE html>
<html>

<head>
    <title>Document Title Example</title>
</head>

<body>
    <p>This is a sample HTML document.</p>
    <button onclick="getDocumentTitle()">Get Document Title</button>
    <button onclick="setDocumentTitle()">Set Document Title</button>

    <script>
        // 获取文档标题
        function getDocumentTitle() {
            var title = document.title;
            alert("Document Title: " + title);
        }

        // 设置文档标题
        function setDocumentTitle() {
            var newTitle = prompt("Enter the new document title:");
            if (newTitle !== null) {
                document.title = newTitle;
            }
        }
    </script>
</body>

</html>

在这个例子中,通过 document.title 属性获取文档的当前标题,然后使用 alert 弹出对话框显示标题。通过 document.title = newTitle 可以设置新的文档标题。在点击 "Get Document Title" 按钮时,会弹出对话框显示当前文档标题;在点击 "Set Document Title" 按钮时,会通过 prompt 获取用户输入的新标题,并将文档标题设置为新的值。


转载请注明出处:http://www.pingtaimeng.com/article/detail/6236/JavaScript 和 HTML DOM