김민태 [프론트엔드 아카데미] 3 - (3)

이동주·2021년 10월 13일
0

두 개의 화면을 가진 웹앱

appendchild와 createElement

(1) createElement

선택한 부분에 요소를 만든다.

.createElement( 'h1' )

=> < h1 >< /h1 >

(2) appendchild

선택한 부분에 자식 태그를 만든다.

	const li = document.createElement('li')
    const a = document.createElement('a');
    
    li.appendChild(a);
    ul.appendChild(li);

=> < ul >
< li >< a >< /a >< /li?
< /ul >

hashchange 이벤트

같은 페이지 안에서 해시(#)만 바뀌었을 때, 즉 페이지에서 id가 있는 요소로 이동했을 때 발생

location 객체

주소와 관련된 다양한 정보 제공

substr

내가 쓰고 싶은 위치 값을 지정해주면 그 이후 값부터만 씀

.substr(1);

=> 인덱스 1부터 불러옴

replace

자리를 바꿔줌

const CONTENTS_URL = 'http://api.hnpwa.com/v0/item/@id.json';
const id = location.hash.substr(1);

.replace('@id', id);

첫 번째는 바꿀 위치, 두 번째는 바꿀 값.

Result

const container = document.getElementById('root');
const ajax = new XMLHttpRequest();
const contents = document.createElement('div');
const NEWS_URL = 'https://api.hnpwa.com/v0/news/1.json';
const CONTENTS_URL = 'http://api.hnpwa.com/v0/item/@id.json';

ajax.open('GET', NEWS_URL, false) // true: 비동기 처리 false: 동기 처리
ajax.send();

const newsFead = JSON.parse(ajax.response);
const ul = document.createElement('ul');

window.addEventListener('hashchange', function () {
    const id = location.hash.substr(1);

    ajax.open('GET', CONTENTS_URL.replace('@id', id), false);
    ajax.send();

    const newsContent = JSON.parse(ajax.response);
    const title = document.createElement('h1');

    title.innerHTML = newsContent.title;

    contents.appendChild(title);
});

for (let i = 0; i < 10; i++) {
    const li = document.createElement('li')
    const a = document.createElement('a');

    a.href = `#${newsFead[i].id}`;
    a.innerHTML = `${newsFead[i].title} (${newsFead[i].comments_count})`;
    
    li.appendChild(a);
    ul.appendChild(li);
}

container.appendChild(ul);
container.appendChild(contents);
profile
안녕하세요 이동주입니다

0개의 댓글