#querySelector: JS로 생명력을 부여할수있는 방법
손흥민 연봉 15억 조절했던것 수업내용 기억하기
해당 class를 가지고 올거다.
#textContent로 불러온건 모두 String type이다.
# buttons.addEventListener('click', function (event) { }
addEventListener는 button click하면 function이 실행된다.는 의미이다
# 일단 계산기모양이 0+0=0 이거다
# firstOperend.textContent를 써야 0이 불러와진다.-> 이러면 첫번째0에 숫자가 들어온다.
firstOperend.textContent = buttonContent;
#operator자리도
operator.textContent = buttonContent;
#첫번째수가 0이 아니면 두번째수에 다음수가 들어온다.
if (firstOperend.textContent !== '0') {
secondOperend.textContent = buttonContent;
} else {
firstOperend.textContent = buttonContent;
}
# if (action === 'clear') {
console.log('초기화 버튼');
firstOperend.textContent = '0';
operator.textContent = '+';
secondOperend.textContent = '0';
calculatedResult.textContent = '0';
}
if (action === 'calculate') {
console.log('계산 버튼');
calculatedResult.textContent = calculate(firstOperend.textContent, operator.textContent, secondOperend.textContent)
}
# let firstNum, operatorForAdvanced, previousKey, previousNum;
이거변수 많은거 보고 눈치채야한다.
변수가 이렇게나온건 이거 다 이용한다는 말이다.
# 여기서는 계산자리가 0으로만 표시되어있다.
한자리숫자만 계산하지않는다.
# number자리
display.textContent = display.textContent + buttonContent;
#만약 디스플레이가 0이면 새로운숫자 입력/ 그렇지 않으면 뒤에다가 이어붙인다.
if(display.textContent === '0') {
display.textContent = buttonContent;}
else {
display.textContent = display.textContent + buttonContent;}
#operator자리
보이지 않는 곳에 연산자를 기억해놔야한다-> 변수가 필요하다는거다 -> operatorForAdvanced
operatorForAdvanced = buttonContent;
//화면에 떠있는 숫자도 기억해야한다.
firstNum = display.textContent;
// 연산자를 눌렀다는 사실도 기억해야 한다.
previousKey = 'operator';
number자리의 if문 수정해야한다.
if(display.textContent === '0' || previousKey === 'operator') {}
#calculate자리
display.textContent = calculate(firstNum, operatorForAdvanced, display.textContent);
//operator가 입력이 되어있을때만 계산실행.
if (operatorForAdvanced){
previousNum = display.textContent;
display.textContent = calculate(firstNum, operatorForAdvanced, previousNum);
previousKey = 'calculate';}
#clear자리
//아무것도 할당하지 않은 상태는 undefined
if (action === 'clear') {
display.textContent = '0';
firstNum = undefined;
operatorForAdvanced = undefined;
previousNum = undefined;
previousKey = 'clear';
}
#뒤에 누르는 숫자가 두자리숫자로 늘리게하기위하여
previousKey = 'number'; 추가한다.
#소수점
//만약에 디스플레이에 소수점이 없으면
if(display.textContent.includes('.') === false) {
display.textContent = display.textContent + '.';
const calculator = document.querySelector('.calculator'); // calculator 엘리먼트와, 그 자식 엘리먼트의 정보를 모두 담고 있습니다.
const buttons = calculator.querySelector('.calculator__buttons'); // calculator__keys 엘리먼트와, 그 자식 엘리먼트의 정보를 모두 담고 있습니다.
const firstOperend = document.querySelector('.calculator__operend--left'); // calculator__operend--left 엘리먼트와, 그 자식 엘리먼트의 정보를 모두 담고 있습니다.
const operator = document.querySelector('.calculator__operator'); // calculator__operator 엘리먼트와, 그 자식 엘리먼트의 정보를 모두 담고 있습니다.
const secondOperend = document.querySelector('.calculator__operend--right'); // calculator__operend--right 엘리먼트와, 그 자식 엘리먼트의 정보를 모두 담고 있습니다.
const calculatedResult = document.querySelector('.calculator__result'); // calculator__result 엘리먼트와, 그 자식 엘리먼트의 정보를 모두 담고 있습니다.
// DOM -> JavaScript로 생명력을 부여할 수 있는 방법
// 손흥민 -> 바꾸는거
function calculate(n1, operator, n2) {
// textContent를 불러오고 있는데, textContent로 불러온 건 모두 string type
let result = 0;
// TODO : n1과 n2를 operator에 따라 계산하는 함수를 만드세요. +, -, * , /
if (operator === '+') {
result = Number(n1) + Number(n2);
} else if (operator === '-') {
result = Number(n1) - Number(n2);
} else if (operator === '*') {
result = Number(n1) * Number(n2);
} else if (operator === '/') {
result = Number(n1) / Number(n2);
}
// ex) 입력값이 n1 : '1', operator : '+', n2 : '2' 인 경우, 3이 리턴됩니다.
return String(result);
}
buttons.addEventListener('click', function (event) {
// 버튼을 눌렀을 때 작동하는 함수입니다.
const target = event.target; // 클릭된 HTML 엘리먼트의 정보가 저장되어 있습니다.
const action = target.classList[0]; // 클릭된 HTML 엘리먼트에 클레스 정보를 가져옵니다.
const buttonContent = target.textContent; // 클릭된 HTML 엘리먼트의 텍스트 정보를 가져옵니다.
// ! 위 코드(Line 19 - 21)는 수정하지 마세요.
if (target.matches('button')) {
// TODO : 계산기가 작동할 수 있도록 아래 코드를 수정하세요. 작성되어 있는 조건문과 console.log를 활용하시면 쉽게 문제를 풀 수 있습니다.
// 클릭된 HTML 엘리먼트가 button이면
if (action === 'number') {
// 그리고 버튼의 클레스가 number이면
// 아래 코드가 작동됩니다.
// 두번째 숫자를 입력하기 위해서 조건이 필요.1
// 만약 첫번째 칸에 숫자가 입력되어 있으면 -> 0이 아니면
if (firstOperend.textContent !== '0') {
secondOperend.textContent = buttonContent;
} else {
firstOperend.textContent = buttonContent;
}
console.log('숫자 ' + buttonContent + ' 버튼');
}
if (action === 'operator') {
operator.textContent = buttonContent;
console.log('연산자 ' + buttonContent + ' 버튼');
}
if (action === 'decimal') {
// console.log('소수점 버튼');
}
if (action === 'clear') {
console.log('초기화 버튼');
firstOperend.textContent = '0';
operator.textContent = '+';
secondOperend.textContent = '0';
calculatedResult.textContent = '0';
}
if (action === 'calculate') {
console.log('계산 버튼');
calculatedResult.textContent = calculate(firstOperend.textContent, operator.textContent, secondOperend.textContent)
}
}
});
// ! Advanced Challenge test와 Nightmare test를 위해서는 아래 주석을 해제하세요.
const display = document.querySelector('.calculator__display--for-advanced'); // calculator__display 엘리먼트와, 그 자식 엘리먼트의 정보를 모두 담고 있습니다.
let firstNum, operatorForAdvanced, previousKey, previousNum;
// 아 이 변수 4개 다 쓰겠구나?
buttons.addEventListener('click', function (event) {
// 버튼을 눌렀을 때 작동하는 함수입니다.
const target = event.target; // 클릭된 HTML 엘리먼트의 정보가 저장되어 있습니다.
const action = target.classList[0]; // 클릭된 HTML 엘리먼트에 클레스 정보를 가져옵니다.
const buttonContent = target.textContent; // 클릭된 HTML 엘리먼트의 텍스트 정보를 가져옵니다.
// ! 위 코드는 수정하지 마세요.
// ! 여기서부터 Advanced Challenge & Nightmare 과제룰 풀어주세요.
if (target.matches('button')) {
if (action === 'number') {
// 만약에 디스플레이가 현재 0이면 새로운 숫자 입력// 그렇지 않으면, 그 뒤에다가 붙인다.
if(display.textContent === '0' || previousKey === 'operator') {
display.textContent = buttonContent; // 새로운 숫자 입력
} else {
display.textContent = display.textContent + buttonContent;
}
previousKey = 'number';
}
if (action === 'operator') {
// 보이지 않는 곳에 연산자를 기억시키려면? 변수
// 화면에 떠있는 숫자도 기억해야하지 않을까?
// 연산자를 눌렀다는 사실도 기억해야 한다.
operatorForAdvanced = buttonContent;
firstNum = display.textContent;
previousKey = 'operator';
}
if (action === 'decimal') {}
if (action === 'clear') {
display.textContent = '0';
firstNum = undefined;
operatorForAdvanced = undefined;
previousNum = undefined;
previousKey = 'clear';
}
if (action === 'calculate') {
// operator가 입력이 되어 있을 때만 계산 실행
if (operatorForAdvanced) {
previousNum = display.textContent;
display.textContent = calculate(firstNum, operatorForAdvanced, previousNum);
previousKey = 'calculate';
}
}
}
});
출처: 코드스테이츠
'코플릿 기록 > JavaScript' 카테고리의 다른 글
객체 20번 ★★★★ (0) | 2022.12.30 |
---|---|
객체 15번 ★★ (0) | 2022.12.30 |
반복문13번 ★★ (0) | 2022.12.21 |
반복문 12번★★ (0) | 2022.12.20 |
반복문 11번★★ (0) | 2022.12.20 |