HackerNews JS(2)

ha·2022년 7월 14일
0

HackerNews JS

목록 보기
2/6

app.js
1. a.href = #${newsFeed[i].id}
2. window.addEventListener('hashchange')으로
3. const container = document.getElementById('root')선언 후 container.appendChild(ul)과 같이 적용

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

ajax.open('GET',NEWS_URL, false);
ajax.send();

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

window.addEventListener('hashchange', function () {
  const id = location.hash.substr(1)
  console.log(id);
  ajax.open('GET', CONTENT_URL.replace('@id', id), false);
  ajax.send();

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

  title.innerHTML = newsContent.title

  content.appendChild(title)
  
})

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

  a.href = `#${newsFeed[i].id}`
  a.innerHTML = `${newsFeed[i].title} (${newsFeed[i].comments_count})`;

  li.appendChild(a);
  ul.appendChild(li);
}
container.appendChild(ul);
container.appendChild(content);

0개의 댓글