[Javascript] History API

const players = [
  {
    id: 'x9Opl1',
    name: 'Mario',
    bio: 'Italian plumber and lead character',
  },
  {
    id: '7fGlZ0',
    name: 'Luigi',
    bio: "Mario's green younger brother",
  },
  {
    id: 'y0SH11',
    name: 'Yoshi',
    bio: 'Green dinosaur turns enemies into eggs',
  },
  {
    id: 'a8Pxia',
    name: 'Wario',
    bio: "Mario's yellow and purple arch-rival",
  },
];

const app = document.getElementById('app');
app.innerHTML = `
  <h1>JavaScript HTML5 APIs</h1>
  <nav class="links">
    ${players.map((player) => `<a href="/${player.id}">${player.name}</a>`)}
  </nav>
  <div class="info"></div>
  <button type="button" class="back">Back</button>
  <button type="button" class="forward">Forward</button>
`;

const info = document.querySelector('.info');
const links = [...document.querySelectorAll('.links a')];
const back = document.querySelector('.back');
const forward = document.querySelector('.forward');

const render = (state) => {
  info.innerHTML = `
    <h3>${state.name}</h3>
    <p>${state.bio}</p>
  `;
};

const pushDefaultState = () => {
  const player = players[0];
  history.replaceState(player, '', player.id);
  render(player);
};

const init = () => {
  if (location.pathname === '/') {
    pushDefaultState();
    return;
  }

  const id = location.pathname.substring(1);
  const player = players.find((player) => player.id === id);

  render(player);
};

back.addEventListener('click', () => history.go(-1));
forward.addEventListener('click', () => history.go(1));

links.forEach((link) => {
  link.addEventListener('click', (e) => {
    e.preventDefault();
    const id = e.target.getAttribute('href').substring(1);
    const player = players.find((player) => player.id === id);

    history.pushState(player, '', player.id);
    render(player);
  });
});

window.addEventListener('popstate', (e) => {
  if (!e.state) {
    pushDefaultState();
    return;
  }

  const player = e.state;
  render(player);
});

if (window.history && window.history.pushState) {
  init();
}

 

posted @ 2021-12-15 17:03  Zhentiw  阅读(75)  评论(0编辑  收藏  举报