如何在 JavaScript 中查詢文件中的連結數量?


在本文中,我們將討論如何在 JavaScript 中查詢文件中的連結數量。

JavaScript 中的 DOM 屬性提供了許多屬性,例如 <head>、<title>、<body>、<link>、<a>、<style>。我們可以透過兩種方式在 HTML DOM 中表示連結。DOM 物件提供 links 屬性。

document.links 屬性為我們提供了文件內 <a> 和 <area> 標籤的集合。document.links 屬性類似於陣列。我們可以使用此屬性訪問連結的任何屬性(如 href、name、title)。要查詢連結的總數,可以使用 length 屬性。document.links.length 為我們提供了文件中連結的總數。

語法

下面顯示了確定文件中連結數量的語法。

document.links.length

示例 1

以下是一個查詢文件中連結數量的示例程式。

<html>
<body>
   <a href="https://tutorialspoint.tw/javascript/index.htm">Javascript</a><br>
   <a href="https://tutorialspoint.tw/php/index.htm">Php</a><br>
   <a href="https://tutorialspoint.tw/java8/index.htm">Php</a><br>
   <p id="links"></p>
   <script>
      document.getElementById("links").innerHTML = "The number of links are: " + document.links.length;
   </script>
</body>
</html>

執行上述程式碼後,將生成以下輸出。

示例 2

以下是如何查詢文件中連結數量的另一個示例程式。

<!DOCTYPE html>
<html>
<head>
   <title>To find the number of links in a document in JavaScript</title>
</head>
<body style="text-align : center">
   <h1>To find the number of links in a document in JavaScript</h1>
   <a name="google" href="https://www.google.com/" title="Google Home Page">Google</a><br>
   <a name="facebook" href="https://#/" title="Facebook Home Page">Facebook</a><br>
   <a name="youtube" href="https://www.youtube.com/" title="Youtube Home Page">Youtube</a><br>
   <p id="text1"></p>
   <script>
      document.getElementById("text1").innerHTML = "The total number of links in the document are : "+document.links.length;
   </script>
</body>
</html>

執行上述程式碼後,將生成以下輸出。

示例 3

以下示例告訴我們每個連結以及連結總數。

<!DOCTYPE html>
<html>
<head>
   <title>To find the number of links in a document in JavaScript</title>
</head>
<body style="text-align : center">
   <h1>To find the number of links in a document in JavaScript</h1>
   <a name="google" href="https://www.google.com/" title="Google Home Page">Google</a><br>
   <a name="youtube" href="https://www.youtube.com/" title="Youtube Home Page">Youtube</a><br>
   <p id="text1"></p>
   <script>
      var result="";
      for(var i=0;i<document.links.length;i++){
         result += "Link "+(i+1)+" : "+document.links[i].href+"<br/>";
      }
      document.getElementById("text1").innerHTML = "The links in the document are : "+'<br/>'+result+'<br/>'+"The count for total number of links is : "+document.links.length;
   </script>
</body>
</html>

執行上述程式碼後,將生成以下輸出。

更新於: 2022-12-08

948 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.