HTML DOM 位置雜湊屬性


Location hash 屬性返回/追加一個字串值(錨點)到一個 URL。錨點自動以“#”為字首,然後追加。

語法

以下是語法:

  • 返回 hash 屬性的值
location.hash
  • 設定 hash 屬性的值
location.hash = ‘string’

示例

讓我們看一個關於 Location hash 屬性的示例:

 線上演示

<!DOCTYPE html>
<html>
<head>
<title>Location hash</title>
<style>
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   * {
      padding: 2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius: 10px;
   }
</style>
</head>
<body>
<form>
<fieldset>
<legend>Location-hash</legend>
<label for="urlSelect">Current URL:</label>
<input type="url" size="27" id="urlSelect" value="https://www.example.com/">
<input type="text" id="textSelect" placeholder="hash value...">
<input type="button" onclick="setHashValue()" value="Go To URL">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
   var divDisplay = document.getElementById("divDisplay");
   var urlSelect = document.getElementById("urlSelect");
   var textSelect = document.getElementById("textSelect");
   function setHashValue() {
      if(textSelect.value !== ''){
         location.hash = textSelect.value;
         urlSelect.value += location.hash;
         divDisplay.textContent = 'Page loaded. Current URL active';
      } else {
         divDisplay.textContent = 'Please provide a hash value';
      }
   }
</script>
</body>
</html>

輸出

這將產生以下輸出:-

點選“轉到 URL”按鈕前:

點選帶有已設定雜湊值的“轉到 URL”按鈕後:

更新於:2019-7-30

157 次瀏覽

開啟你的 職業生涯

透過完成課程獲取證書

開始
廣告
© . All rights reserved.