목차
- hash 예제 - URL의 해시(= #부분) 반환
- hash 정의
- hash 구문
- hash 예제 - URL의 해시(= #부분) 설정
hash 예제 - URL의 해시(= #부분) 반환
[예제1]
<p><a id="js" href="https://homzzang.com/b/js#hz">JavaScript</a><p>
<p id="demo"></p>
<script>
let url = document.getElementById("js");
document.getElementById("demo").innerHTML = url.hash;
</script>
결과보기 (결과값: #hz)
[예제2]
현재 URL 주소가 아래와 같은 경우.
https://homzzang.com/b/js#hz
<script>
var x = location.hash;
document.write(x); // 결과값: #hz
</script>
hash 정의
URL (앵커)의 해시(# 기호 부분) 설정/반환.
1.
주의: hash 값 설정할 땐 # 기호 안 붙임. (출력 시 자동으로 추가됨)
2.
주요 브라우저 모두 지원.
hash 구문
[반환]
location.hash
[설정]
location.hash = anchorName
[속성값]
anchorName
필수. URL anchor 부분의 문자열 지정. (#기호 빼고 입력)
hash 예제 - URL의 해시(= #부분) 설정
<button onclick="homzzang()">클릭</button>
<p id="demo"></p>
<script>
function homzzang() {
location.hash = "hz"; // 주의: 설정할 땐 #기호 없이 입력
var x = location.hash;
document.getElementById("demo").innerHTML = x; // #hz
}
</script>
결과보기