如何在 JavaScript 中获取文档的标题和完整 URL?


在本文中,我们将学习如何使用 JavaScript 获取文档的标题和完整 URL,并辅以示例。

Javascript HTML DOM 提供了一些基本方法来访问和操作 HTML 数据。要查找文档的标题和URL,JavaScript 分别提供了document.titledocument.URL

document.title 属性 - document.title 属性返回文档的当前标题。此属性适用于 HTML、SVG、XUL 和其他文档。获取文档标题的语法如下所示。

document.title

document.url 属性 - Document 接口的 URL 只读属性返回文档的完整 URL。即,文档的位置作为一个字符串,包括协议 (http://)。它类似于 Window 对象属性location.href,该属性返回当前页面的 URL。获取文档完整 URL 的语法如下所示。

document.URL or document.documentURI

让我们看一些示例 -

示例 1

使用document.title 属性

以下是关于如何获取文档标题的示例程序。

<!DOCTYPE HTML>
<html>
<head>
   <title>How to know the Title and URL of document in JavaScript</title>
</head>
   <body style = "text-align:center;">
      <h3>A sample program to know title of a document</h3>
      <p id="text1"></p>
      <script type="text/javascript">
         document.getElementById("text1").innerHTML = "The Document's Title is : "+document.title;
      </script>
   </body>
</html>

执行上述代码后,将生成以下输出。

示例 2

当我们将文本分配给document.title 时,文档的标题将更改。此功能在以下示例中进行了演示。

<!DOCTYPE HTML>
<html>
<head>
   <title>How to know the Title and URL of document in JavaScript</title>
</head>
<body style = "text-align:center;">
   <h3>A sample program to know title of a document</h3>
   <p id="text1"></p>
   <script type="text/javascript">
      document.title = " New Title : A program to know the title of a document";
      document.getElementById("text1").innerHTML = "The Document's New Title is : "+document.title;
   </script>
</body>
</html>

执行上述代码后,将生成以下输出。

示例 3

使用 document.url 属性

以下是关于如何获取文档完整 URL 的示例程序。

<!DOCTYPE HTML>
<html>
<head>
   <title>How to know the Title and URL of document in JavaScript</title>
</head>
<body style = "text-align:center;">
   <h3>A sample program to know the FULL URL of a document</h3>
    <p id="text1"></p>
   <script type="text/javascript">
      var url = location.href;
      var docURL = document.URL;
      document.getElementById("text1").innerHTML = "The Location of the Document is : "+docURL+"<br />"+"The document location by using Window object property : "+url;
   </script>
</body>
</html>

执行上述代码后,将生成以下输出。

更新于: 2022-12-08

1K+ 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.