강의

멘토링

로드맵

Inflearn brand logo image

인프런 커뮤니티 질문&답변

미갱이님의 프로필 이미지
미갱이

작성한 질문수

아래 질문 (토이스토리 title의 button태그에 링크거는 방법)에 대해 해결법이 이게 맞을까요? 더 좋은 방법 알려주세요~

작성

·

12

0

navList.forEach((li, index)=>{

  const roma = ['I', 'II', 'III'];
  const arabic = ['1','2','3']
  const linkAddr = ['naver.com','google.com','inflearn.com'];  // button 링크 주소

  li.addEventListener('click',()=>{

    if(!playing) {
      next = index;

      if(li.classList.contains('active')) return;
      for(let i=0;i < navList.length; i++) {
        navList[i].classList.remove('active');
      }
      li.classList.add('active');

      const addr = /*html*/`location.href='http://${linkAddr[next]}'`;  // button 속성 값

      const tl = gsap.timeline()
      .add(leave[current].play())
      .add(titleLeave.play(),'-=1')
      .set('.title h1',{text:`toystory ${roma[index]}`})
      .set('.title p',{text:`토이스토리 시즌 ${arabic[index]}`},'<')
      .add(enter[next].play())
      .add(titleEnter.play())

      tl.eventCallback('onComplete',()=>{
        const btnLink = document.querySelector('.title button');  // button 요소 가져오기
        btnLink.setAttribute('onclick',addr);   // button의 onclick 속성 추가
        current = next;
        playing = false;
      })

      playing = true;
    }
  })
    
    
})



window.addEventListener('load',()=>{

  
  const tl = gsap.timeline()

  .add(enter1.play())  // enter 타임라인 실행
  .add(titleEnter.play())

  tl.eventCallback('onComplete', () => { 
    const btnLink = document.querySelector('.title button');  //처음 실행시 button에 속성값 추가
    btnLink.setAttribute('onclick',"location.href='http://naver.com'"); //처음 실행시 button에 속성값 추가
    playing = false; 
  })

  // page03()[1].play()  // enter 타임라인 실행


})

답변 1

0

안녕하세요, 인프런 AI 인턴입니다.
미갱이님께서 질문하신 링크를 버튼 태그에 추가하는 방법에 대해 답변드리겠습니다.

제안하신 방법도 작동하겠지만, onclick 속성을 사용하지 않고, DOM 이벤트 리스너를 이용해 직접 클릭 이벤트를 처리하는 방식이 더 추천됩니다. 이렇게 하면 코드의 유지보수성과 가독성이 향상됩니다. 아래는 개선된 예시입니다.

navList.forEach((li, index) => {
  const roma = ['I', 'II', 'III'];
  const arabic = ['1','2','3'];
  const linkAddr = ['https://naver.com', 'https://google.com', 'https://inflearn.com'];  // button 링크 주소

  li.addEventListener('click', () => {
    if(!playing) {
      next = index;

      if(li.classList.contains('active')) return;
      for(let i = 0; i < navList.length; i++) {
        navList[i].classList.remove('active');
      }
      li.classList.add('active');

      const tl = gsap.timeline()
        .add(leave[current].play())
        .add(titleLeave.play(), '-=1')
        .set('.title h1', {text: `toystory ${roma[index]}`})
        .set('.title p', {text: `토이스토리 시즌 ${arabic[index]}`}, '<')
        .add(enter[next].play())
        .add(titleEnter.play())

      tl.eventCallback('onComplete', () => {
        const btnLink = document.querySelector('.title button');  // button 요소 가져오기
        btnLink.onclick = () => {
          window.location.href = linkAddr[next];
        };
        current = next;
        playing = false;
      });

      playing = true;
    }
  });
});

window.addEventListener('load', () => {
  const tl = gsap.timeline()
    .add(enter1.play())  // enter 타임라인 실행
    .add(titleEnter.play());

  tl.eventCallback('onComplete', () => {
    const btnLink = document.querySelector('.title button');  //처음 실행시 button에 속성값 추가
    btnLink.onclick = () => {
      window.location.href = 'https://naver.com'; // 처음 실행시 링크 추가
    };
    playing = false;
  });
});

이 코드에서는 onclick 속성을 문자열로 설정하는 대신, window.location.href를 직접 설정하는 클릭 이벤트를 정의합니다. 이렇게 하면 보안과 코드 가독성이 개선되며, 이벤트 리스너를 활용함으로써 유지보수도 쉬워집니다.

도움이 되었길 바랍니다! 추가 질문이 있다면 언제든지 말씀해 주세요.

미갱이님의 프로필 이미지
미갱이

작성한 질문수

질문하기