HTML DOM Location host 属性
htmlweb developmentfront end technology更新于 2025/7/18 0:12:17
Location host 属性返回/设置主机名和主机端口(如果指定)。如果未明确指定,端口可能不会显示。
语法
以下是语法 −
- host属性的返回值
location.host
- host属性的值
location.host = hostname:host
示例
让我们看一个Location host属性的示例 −
<!DOCTYPE html>
<html>
<head>
<title>Location host</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-host</legend>
<label for="urlSelect">Current URL:</label>
<input type="url" size="27" id="urlSelect" value="https://www.example.com:2544">
<input type="button" onclick="getHostPort()" value="Get Port">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var urlSelect = document.getElementById("urlSelect");
function getHostPort() {
if(location.host.includes(':') === false)
divDisplay.textContent = 'No port present, as host: '+location.host;
else
divDisplay.textContent = 'Port: '+location.host.split(":")[1]+', as host: '+location.host;
}
</script>
</body>
</html>
输出
这将产生以下输出 −
点击 ‘获取端口’ 按钮前 −

点击‘获取端口’按钮后 −

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

