Computer >> Máy Tính >  >> Lập trình >> HTML

HTML DOM Location Replace () phương thức

Phương thức HTML DOM Location Replace () được sử dụng để hiển thị một tài liệu mới thay thế tài liệu hiện tại. Nó cũng xóa URL của tài liệu hiện tại khỏi lịch sử tài liệu, vô hiệu hóa điều hướng đến tài liệu cũ bằng cách sử dụng ‘back’ nút.

Cú pháp

Sau đây là cú pháp -

location.replace(URLString)

Ví dụ

Hãy để chúng tôi xem một ví dụ về Vị trí thay thế () tài sản -

<!DOCTYPE html>
<html>
<head>
<title>Location replace()</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-replace( )</legend>
<label for="urlSelect">Current URL: </label>
<input type="url" id="urlSelect" value="https://www.example.com"><br>
<label for="newUrlSelect">New URL: </label>
<input type="url" id="newUrlSelect" placeholder="Give new url..."><br>
<input type="button" onclick="doReplace()" value="Go to new URL">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
   var divDisplay = document.getElementById("divDisplay");
   var urlSelect = document.getElementById("urlSelect");
   var newUrlSelect = document.getElementById("newUrlSelect");
   function doReplace(){
      if(newUrlSelect.value === '')
         divDisplay.textContent = 'Provide new URL';
      else{
         location.replace(newUrlSelect.value);
         divDisplay.textContent = 'Redirecting to new URL';
      }
   }
</script>
</body>
</html>

Đầu ra

Điều này sẽ tạo ra kết quả sau -

Sau khi nhấp vào ‘Chuyển đến URL mới’ nút không có đầu vào -

HTML DOM Location Replace () phương thức

Nhấp vào ‘Chuyển đến URL mới’ nút sau khi điền thông tin chi tiết -

HTML DOM Location Replace () phương thức