JavaScript - BOM Location trong Javascript

by My Love

28/03/2019, 8:45 AM   |    28/03/2019, 8:45 AM   |    811   |    0

      Location là một thuộc tính của đối tượng window dùng để sử lý, điều hướng các url của trang web. Được viết với cú pháp :
window.location
Ta cùng tìm hiểu một số thuộc tính và phương thức của location
1. Các thuộc tính của location
Thuộc tính Chức năng
hash Gán hoặc lấy phần sau của dấu # trong url
host Gán hoặc lấy hostname và port number trong url
hostname Gán hoặc lấy hostname
href Gán hoặc lấy url
protocol Trả về giao thức web sử dụng ( http: hoặc https: )
origin Trả về protocol, hostname và port của url
pathname Gán hoặc lấy pathname của url
port Gán hoặc lấy port của url
search Lấy query string của url

Ví dụ :Các bạn xem ví dụ sau sẽ thấy rõ hơn
	<script language="javascript">
        document.write("hash: " +window.location.hash + "<br />");
        document.write("host: " +window.location.host + "<br />");
        document.write("hostname: " +window.location.hostname + "<br />");
        document.write("href: " +window.location.href + "<br />");
        document.write("protocol: " +window.location.protocol + "<br />");
        document.write("origin: " +window.location.origin + "<br />");
        document.write("pathname: " +window.location.pathname + "<br />");
        document.write("port: " +window.location.port + "<br />");
        document.write("search :" +window.location.search + "<br />");
      </script>

2. Một số phương thức trong location
Phương thức reload()
     Phương thức này giúp tải lại trang web. Cú pháp như sau :
window.location.reload();
Ví dụ :
<html>
    <head>
        
        <script type="text/javascript">
            function Refresh(){
                window.location.reload();
            }
        </script>
    </head>
    <body>
         <input type="button" value="Click Refresh" onclick="Refresh()" /> 
    </body>
</html>
Phương thức replace() , assign()
      Phương thức này giúp điều hướng url giống với thuộc tính href ở trên. Tuy nhiên với replace() thì trình duyệt sẽ không lưu vào lịch sử.
Ví dụ :
<html>
    <head>
        
    </head>
    <body>
        <input type="button" value="replace Url" onclick="replace()" />
        <input type="button" value="assign Url" onclick="assign()" />
        <input type="button" value="href Url" onclick="href()" />
        <script language="javascript">
            function replace(){
                window.location.replace('http://vnfree.net');
            }
            function assign(){
                window.location.assign('http://vnfree.net');
            }
            function href(){
                window.location.href = 'http://vnfree.net';
            }
          </script>
    </body>
</html>