Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

คุณสมบัติ port ของ Location ใน HTML DOM

คุณสมบัติ port ของ Location ใช้สำหรับอ่านหรือตั้งค่าหมายเลขพอร์ตของ URL (อาจไม่แสดงหากไม่ได้ระบุชัดเจน)

ไวยากรณ์ (Syntax)

การอ่านค่า

location.port

การตั้งค่า

location.port = portNumber

ตัวอย่างการใช้งาน

ตัวอย่างด้านล่างแสดงพอร์ตของ URL ปัจจุบัน:

<!DOCTYPE html>
<html>
<head>
<title>Location port</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-port</legend>
    <label for="urlSelect">Current URL:</label>
    <input type="url" size="30" id="urlSelect" value="https://www.example.com:2544/aboutUs/CTO.htm">
    <input type="button" onclick="getport()" value="Get Port">
    <div id="divDisplay"></div>
  </fieldset>
</form>
<script>
  var divDisplay = document.getElementById("divDisplay");
  var urlSelect = document.getElementById("urlSelect");
  
  function getport() {
    divDisplay.textContent = 'URL port: ' + location.port;
  }
</script>
</body>
</html>

ผลลัพธ์

ก่อนคลิกปุ่ม "Get Port": แสดง URL และปุ่ม

หลังคลิกปุ่ม "Get Port": แสดง "URL port: 2544" (จาก URL ตัวอย่าง) หรือว่างถ้าไม่มีพอร์ตระบุ

หมายเหตุ: รูปภาพตัวอย่างจากต้นฉบับไม่ได้รวมอยู่ในเนื้อหานี้