하루하루 배운것들

[8]자바스크립트로 랜덤 명언 띄우기 구현

Personable_d 2020. 1. 5. 02:53

quote.js

 

const quotes = [

  {

    quotation:

      "“If you don't make mistakes, you're not working on hard enough problems. And that's a mistake.”",

    author: "― Frank Wilczek"

  },

  {

    quotation:

      "“It does not matter how slowly you go as long as you do not stop.”",

    author: "-Confucius"

  },

  {

    quotation: "Only I can change my life. No one can do it for me.”",

    author: "-Carol Burnett"

  }

];

//명언들 배열 안에 넣어주기(배열 하나하나는 명언과 이름이 든 객체 형태로)

 

function getRandomQuote() {

  let random = quotes[Math.floor(Math.random() * quotes.length)];

  quotation.innerText = random.quotation;

  author.innerText = random.author;

  return random;

}

//랜덤 으로 문장을 뽑는 함수 만들고, 뽑아진 문장을 paintQuote() 함수를 통해 나타내기

function init() {

  getRandomQuote();

}

//최종 함수 실행!

init();

 

한가지 의문이 드는 건

 

  quotation.innerText = random.quotation;

  author.innerText = random.author; 이 부분에서

 

quotation과 author는 html에서 지정한 id이름인데 이걸 js파일에 참조시키려면 원칙적으로는

전역으로 const quotation = document.querySelector("#quotation"); 를 써주어 id값을 js에서 쓸 수 있게 가져와야 되는 것 같은데... 이걸 써주지 않아도 알아서 참조가 되네...? 흠.. 왜 그런지 좀 더 알아봐야겠다.

 

코딩 시 참고한 동영상, 사이트

https://youtu.be/0poDnc5X7Zk

https://codepen.io/zsumair/pen/jVjGEQ

 

JavaScript Random Quotes

...

codepen.io

다음에는 API를 가져와서 명언을 띄우는 방식으로 만들어봐야겠다.

 

아래는 명언이 보이는 내 투두 사이트인데, 계속 조금씩 발전시킬 예정이다..

css부분이라던지 디테일한 기능 추가(복사 기능, 공유 기능, 분석...) 라던지 할 거 천지다.

여유 생길 때마다 추가해야지~

https://personabled.github.io/JS-BASIC/

 

JavaScript | Todo

 

personabled.github.io