Hash

기초/Node.js|2021. 8. 17. 21:12

어떤 페이지에 접근할 때는 URL을 통해 접근할 수 있다.

단, 페이지 안에서 어떤 특정한 부분으로 접근하고 싶을 때는?

 

예를 들어, 3개의 문단으로 구성된 글이 어떤 페이지(hash.html)내에 있고,

어떤 URL을 통해 그 페이지에 접근했을 때 3번째 문단을 기준으로 접근하고 싶다고 하자.

<p id="tenten">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
  Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
  when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
  It has survived not only five centuries, but also the leap into electronic typesetting, 
  remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets 
  containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker 
  including versions of Lorem Ipsum.
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
  Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
  when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
  It has survived not only five centuries, but also the leap into electronic typesetting, 
  remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets 
  containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker 
  including versions of Lorem Ipsum.
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
  Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
  when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
  It has survived not only five centuries, but also the leap into electronic typesetting, 
  remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets 
  containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker 
  including versions of Lorem Ipsum.
</p>

위처럼 식별하고 싶은 문단(부분,fragment)에 id값(fragment identifier)을 부여하고,
/hash.html#${id값} 으로 요청을 하면

해당 id와 일치하는 요소의 위치로 이동하게 된다. 

 

hash값이 무엇이냐에 따라서 Ajax로 다른 페이지를 로드해서

시작되는 페이지를 세팅할 수도 있다.

 

그럼 그 Hash값이 무엇인지는 어떻게 알 수 있을까? → 참고링크

<script>
  if (location.hash){
    // Fragment exists
    console.log(location.hash);
    console.log(location.hash.substr(1));
  } else {
    // Fragment doesn't exist
  }
</script>

위처럼 location.hash를 찍어 주면 해당 페이지의 해시값을 알려 준다.

앞의 #를 떼고 싶으면.. substring함수를 이용하면 된다. → 참고링크

 

<ol>
  <li>
      <a href="#!html" onclick="fetchPage('html')">HTML</a>
  </li>
  <!--<li><a href="1.html">HTML</a></li>-->
  <li>
      <a href="#!css" onclick="fetchPage('css')">CSS</a>
  </li>
</ol>
<article></article>
<script>
  function fetchPage(topicName) {
    fetch(topicName).then(function(response) {
      response.text().then(function(text) {
        document.querySelector("article").innerHTML = text;
      });
    });
  }

  if (location.hash){
    // hash값이 있다면?
    console.log(location.hash.substr(2));
  } else {
    // hash값이 없을 경우
    fetchPage("Welcome");
  }
</script>

결과적으로 이렇게 하면 됨~.~

맨 밑에 if문까지 해주면 웰컴페이지 세팅도 가능하다.

 

+

관습적으로 해시값 앞에는 #! 을 써주는데, Hashbang이라고 함.

(최근에는 좀 더 진화된 방식으로 pjax라는 기술을 사용한다.)

 

++

리스트 일일이 구현하지 않고 리스트라는 파일을 따로 관리하는 방법

fetch("list").then(function(response) {
    //리스트 파일에서 똑같은 걸 읽어올 것
    response.text().then(function(text){
        // <li> <a href="#!html" onclick="fetchPage('html')">HTML</a></li>
        // list라는 파일을 따로 만들고, 콤마를 구분자로 해서 위 형식에 따라 만들어 주고 
        // 그것을 innerHTML해줘보자.
        // 배열을 만들고 반복문에 따라 하나씩 꺼내서 리스트로 만들 수 있다.
        console.log(text);
        console.log(text.split(",")); // ,를 기준으로 텍스트를 나눠서 배열로 만들어 준다.
        var items = text.split(",");
        var i = 0;
        var tags = "";
        while(i<items.length){
            var item = items[i];
            var tag = 
                '<li> <a href="#!' +
                item +
                '"onclick="fetchpage(\'' +
                item +
                "')\">" +
                item +
                "</a></li>";
            console.log(tag);
            tags = tags + tag;
            i += 1;
        }
        document.querySelector("#nav").innerHTML = tags; 
        // 파일명이 아니라 id값이 nav인 것으로 가져올 거니까 앞에 # 붙여줌
    });
});

https://stackoverflow.com/questions/24282158/javascript-how-to-remove-the-white-space-at-the-start-of-the-string

'기초 > Node.js' 카테고리의 다른 글

노드의 정의, 특성  (0) 2021.08.31
fetch API  (0) 2021.08.16
[Express] 보안과 express generator  (0) 2021.07.17

댓글()