我正在尝试构建一个计算器,此时需要“收集”在数组中单击的任何数字。现在我不确定在哪里构建那个数组(它应该是在一个不同的函数中吗?)。我想我需要使用.push(),但知道我需要在数组上使用它,并且不确定在哪里定义它。当我在console.log(gridItems)时,显然我得到所有,但只想要数字......
/*Calculator
function add(n, x) {
return n + x;
}
console.log(add(3, 8));
function subtract(n, x) {
return n - x;
}
console.log(subtract(3, 8));
function multiply(n, x) {
return n * x;
}
console.log(multiply(3, 8));
function divide(n, x) {
return n / x;
}
console.log(divide(3, 8));*/
// console.log number when button is clicked
function getValue(e){
var divValue = parseInt(e.target.textContent);
console.log(divValue);
}
function numberTrack() {
var gridItems = document.getElementsByClassName('grid');
for (var i = 0; i < gridItems.length; i ++) {
gridItems[i].onclick = getValue;
}
}
numberTrack();
#grid-container {
width: 200px;
}
.grid {
width: 50px;
height: 50px;
display: inline-block;
text-align: center;
}
.gray {
background-color: #ccc;
}
.pink {
background-color: pink;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<div id="grid-container" data-value="1">
<div class="grid gray">0</div>
<div class ="grid pink">1</div>
<div class="grid gray">2</div>
<div class ="grid pink">3</div>
<div class="grid gray">4</div>
<div class ="grid pink">5</div>
<div class="grid gray">6</div>
<div class ="grid pink">7</div>
<div class="grid gray">8</div>
<div class ="grid pink">9</div>
</div>
</head>
<body>
</body>
</html>
答案 0 :(得分:1)
您可以在全球范围内定义它,如下所示:
var clickedNumbers = []
function getValue(e) {
var divValue = parseInt(e.target.textContent);
clickedNumbers.push(divValue);
}
function numberTrack() {
var gridItems = document.getElementsByClassName('grid');
for (var i = 0; i < gridItems.length; i++) {
gridItems[i].onclick = getValue;
}
}
numberTrack();
然后按clickedNumbers
clickedNumbers.push(divValue)