1 回答
TA贡献1801条经验 获得超8个赞
你失踪了三个
1) 使 querySelector 成为 Nodelist 的 querySelectorAll
2) 在 btns[i] 之外写这个
3)初始化你的 currOp.value
const btns = document.querySelectorAll('.btn');
const prevOp = document.querySelector('.previous_op');
const currOp = document.querySelector('.current_op');
const equalBtn = document.querySelector('.equalBtn');
const clearBtn = document.querySelector('.clearBtn');
const deleteBtn = document.querySelector('.delBtn');
currOp.value="";
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
let number= this.getAttribute('data-num');
currOp.value += number;
currOp.innerHTML=currOp.value;
console.log( currOp.value)
})
}
equalBtn.addEventListener('click', function() {
let value = eval(currOp.value);
currOp.value = value;
currOp.innerHTML=currOp.value;
})
clearBtn.addEventListener('click', function() {
currOp.value = '';
currOp.innerHTML='';
})
<!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport">
<title>Calculator</title>
</head>
<body>
<section class="calculator">
<form>
<div class="previous_op"></div>
<div class="current_op"></div>
</form>
<button class ='clearBtn span-two'>AC</button>
<button class ='delBtn'>DEL</button>
<button class='btn btn-orange' data-num='/'>/</button>
<button class='btn btn-grey' data-num='1'>1</button>
<button class='btn btn-grey' data-num='2'>2</button>
<button class='btn btn-grey' data-num='3'>3</button>
<button class='btn btn-orange' data-num='*'>*</button>
<button class='btn btn-grey' data-num='4'>4</button>
<button class='btn btn-grey' data-num='5'>5</button>
<button class='btn btn-grey' data-num='6'>6</button>
<button class='btn btn-orange' data-num='+'>+</button>
<button class='btn btn-grey' data-num='7'>7</button>
<button class='btn btn-grey' data-num='8'>8</button>
<button class='btn btn-grey' data-num='9'>9</button>
<button class='btn btn-orange' data-num='-'>-</button>
<button class='btn btn-grey' data-num='.'>.</button>
<button class='btn btn-grey' data-num='0'>0</button>
<button class ='span-two equalBtn'>=</button>
</section>
</body>
</html>
添加回答
举报