如何在 JavaScript 中獲取文件的標題和完整 URL?
在本文中,我們將學習如何使用 JavaScript 獲取文件的標題和完整 URL,並輔以示例。
Javascript HTML DOM 提供了一些基本方法來訪問和操作 HTML 資料。要查詢文件的標題和URL,JavaScript 分別提供了document.title 和document.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>
執行上述程式碼後,將生成以下輸出。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP