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

ความแตกต่างระหว่าง window.location.href, window.location.replace และ window.location.assign ใน JavaScript

ออบเจกต์ window.location มีเมธอดและคุณสมบัติสำหรับจัดการ URL และการนำทางหน้าเว็บ:

window.location.href

คืนค่า URL ปัจจุบันของหน้าเว็บ และสามารถกำหนดค่าเพื่อนำทางไปยัง URL ใหม่ได้ (เพิ่มเข้า history stack)

<!DOCTYPE html>
<html>
  <body>
    <p>Click below to get the complete URL of the page.</p>
    <button onclick="display()">URL</button>
    <script>
      function display() {
        var res = location.href;
        document.write(res);
      }
    </script>
  </body>
</html>

window.location.replace

นำทางไปยัง URL ใหม่โดย แทนที่ หน้าปัจจุบันใน history stack (ไม่สามารถกด Back กลับมาได้)

<!DOCTYPE html>
<html>
  <body>
    <button onclick="display()">Replace current document</button>
    <script>
      function display() {
        location.replace("https://www.example.com");
      }
    </script>
  </body>
</html>

window.location.assign

โหลดเอกสารใหม่และ เพิ่ม เข้า history stack (สามารถกด Back กลับมาได้)

<!DOCTYPE html>
<html>
  <body>
    <button onclick="display()">Open new document</button>
    <script>
      function display() {
        location.assign("https://www.example.com");
      }
    </script>
  </body>
</html>