무엇을 만드나?
어떤 개체안에 인용문구가 들어가 있고 인용문구를 화면에 랜덤하게 출력시키는 기능
인용문구 출력 기능
html
<body>
<button type="button" id="btn">클릭</button>
<h1 id="quote">인용문구가 들어갈 자리</h1>
<span id="author">작가가 들어갈 자리</span>
</body>
js에 id 가져오기
var quote = document.getElementById('quote');
var author = document.getElementById('author');
var btn = document.getElementById('btn');
인용문구를 배열안에 객체형태로 넣기
var arr = [
{
quote: "아이들은 누구나 예술가이다.",
author: "피카소"
},
{
quote: "내면의 목소리는 들리지 않게 된다.",
author: "반 고흐"
},
{
quote: "완벽을 두려워하지 말라.",
author: "달리"
},
{
quote: "영감이 오는 것을 기다리고 있을 수는 없다.",
author: "런던"
},
{
quote: "의욕만 있으면 이런 노력만으로도 얼마든지 많으 ㄴ생각을 찾을 수 있다.",
author: "수스"
},
];
만약 여기서 배열 0번째 데이터에 특정데이터(quote)에 접근하고 싶으면?
배열 접근공식 + 개체 접근공식 결합
console.log(arr[0].quote);
완성
0 ~ 1 미만의 랜덤 숫자에 arr배열 데이터 갯수를 곱한다음 소수점 값을 내린 값을 random 변수에 클릭시 넣도록함
textContent를 이용해서 자바스크립트에 텍스트 사용
random 변수는 데이터 좌표로 활용됨
btn.addEventListener('click', function(){
var random = Math.floor(Math.random() * arr.length);
quote.textContent = arr[random].quote;
author.textContent = arr[random].author;
});
