웹개발/HTML

window location / button onclick

끈끈 2023. 3. 6. 16:54

 

페이지를 이동하기 위한 방법

 

window location

 

window.location.href = '~'
새 페이지로 이동 - 속성
주소 히스토리가 기록됨

 

window.location.replace('~')
기존 페이지를 새 페이지로 변경 - 메서드
주소 히스토리가 기록되지 않음

 

window 함수 정리

 

EX) https://papago.naver.net/website?locale=ko

 

window.location
👉 https://papago.naver.net/website?locale=ko
현재 페이지의 href(URL) 반환

 

window.location.href
👉 https://papago.naver.net/website?locale=ko
현재 페이지의 href(URL) 반환

 

window.location.protocol
👉 https:
웹 프로토콜(http: / https:) 반환

 

window.location.hostname
👉 papago.naver.net
웹 호스트명(=도메인명) 반환

 

window.location.pathname
👉 /website?locale=ko
현재 페이지의 경로와 파일명 반환

 

window.location.assign("~")
현재창에서 새 URL 주소로 이동
뒤로 가기 가능
마우스 허버시 URL 주소 노출 안 됨

 

여기서, window.location과 location의 차이!

 

window는 생략할 수 있는 기본 namespace라고 한다.

 

따라서 window.location.href()와 location.href()는 같은 코드!

 

하지만 잘못된 참조를 막기 위하여 window를 붙여주는 것이 좋다.

 


 

button onclick

 

onclick="location.href='~'"
현재 페이지에 열기

 

<button onclick="location.href='main.html'">돌아가기</button>
<button onclick="location.href='https://sw-ing.tistory.com/'">돌아가기</button>

 

onclick="window.open('~')"
새 창으로 열기

 

<button onclick="window.open('main.html')">돌아가기</button>
<button onclick="window.open('https://sw-ing.tistory.com/')">돌아가기</button>

 

'웹개발 > HTML' 카테고리의 다른 글

HTML 이미지에 링크 걸기  (0) 2023.03.07
비밀번호 암호화 HASH  (0) 2023.03.07
html _ 클래스(class)와 아이디(id)의 차이  (0) 2023.03.05