gpt4 book ai didi

javascript - 在点击事件上将数字插入数组

转载 作者:行者123 更新时间:2023-12-03 08:19:54 25 4
gpt4 key购买 nike

我正在尝试构建一个计算器,此时需要“收集”数组中单击的所有数字。现在我不确定在哪里构建该数组(它应该在不同的函数中吗?)。我想我需要使用 .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>

最佳答案

您可以在全局范围内定义它,如下所示:

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.push(divValue)将点击的数字插入数组clickedNumbers

关于javascript - 在点击事件上将数字插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33787253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com