Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Phương thức replace() của Location trong HTML DOM

Phương thức replace() của Location trong HTML DOM được dùng để tải một tài liệu mới thay thế tài liệu hiện tại. Nó cũng xóa URL tài liệu hiện tại khỏi lịch sử trình duyệt, vô hiệu hóa việc quay lại tài liệu cũ bằng nút 'back'.

Cú pháp

location.replace(URLString)

Ví dụ

Ví dụ minh họa phương thức Location replace():

<!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">URL hiện tại: </label> <input type="url" id="urlSelect" value="https://www.example.com"><br> <label for="newUrlSelect">URL mới: </label> <input type="url" id="newUrlSelect" placeholder="Nhập url mới..."><br> <input type="button" onclick="doReplace()" value="Đi đến URL mới"> <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 = 'Cung cấp URL mới'; else{ location.replace(newUrlSelect.value); divDisplay.textContent = 'Redirecting to new URL'; } } </script> </body> </html>

Kết quả

Sau khi nhấn nút 'Đi đến URL mới' không có đầu vào:

Phương thức replace() của Location trong HTML DOM

Nhấn nút 'Đi đến URL mới' sau khi điền chi tiết:

Phương thức replace() của Location trong HTML DOM