HTML DOM Location replace() 方法
htmlweb developmentfront end technology更新于 2025/7/19 19:56:17
HTML DOM Location replace() 方法用于渲染一个新文档来替换当前文档。它还会从文档历史记录中删除当前文档的 URL,从而禁用使用 "后退" 按钮导航到旧文档的功能。
语法
以下是语法 −
location.replace(URLString)
示例
让我们看一个 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">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>
输出
这将产生以下输出 −
点击"转到新 URL"按钮后无需输入任何内容 −

填写详细信息后点击"转到新网址"按钮 −

相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

