如何使用vanillaJS用单个函数生成多个东西



在下面的代码段中,我在加载时生成一道数学题,如果单击新建问题按钮,该问题将刷新为一道新问题。

我希望3个问题能够显示在页面上。在伪代码中,这将是:

CCD_ 1。

这就是我到目前为止所做的,但我没有得到我需要的结果。

let getAddition = () => {
let max = 10;
let rand1 = Math.floor(Math.random() * 10) + 1;
let rand2 = Math.floor(Math.random() * 10) + 1;
let sum = rand1 + rand2;
let problems = document.querySelectorAll('.problems');

problems.forEach((problem) => {
problem.textContent = `${rand1} + ${rand2} = ${sum}`;
});
};
window.addEventListener('onload', getAddition());
newProblem.onclick = () => {
getAddition();
};
<button type="button" id="newProblem">New Problem</button>
<div class="container">
<div class="problem"></div>
<div class="problem"></div>
<div class="problem"></div>  
</div>

首先应该是选择器。.problem是你班上的。

第二件事,在循环中移动随机数计算,得到不同的问题。

let getAddition = () => {
let max = 10;

let problems = document.querySelectorAll('.problem');

problems.forEach((problem) => {
const rand1 = Math.floor(Math.random() * 10) + 1;
const rand2 = Math.floor(Math.random() * 10) + 1;
const sum = rand1 + rand2;
problem.textContent = `${rand1} + ${rand2} = ${sum}`;
});
};
window.addEventListener('onload', getAddition());
newProblem.onclick = () => {
getAddition();
};
<button type="button" id="newProblem">New Problem</button>
<div class="container">
<div class="problem"></div>
<div class="problem"></div>
<div class="problem"></div>  
</div>

Shri Hari L的解决方案可以进一步缩短为:

const problems=document.querySelectorAll('.problem');
window.onload=document.getElementById("newProblem").onclick=()=>{
const max = 10;      
problems.forEach((problem) => {
const [rand1,rand2] = [1,2].map(_=>Math.floor(Math.random() * max) + 1);
problem.textContent = `${rand1} + ${rand2} = ${rand1+rand2}`;
});
};
<button type="button" id="newProblem">New Problem</button>
<div class="container">
<div class="problem"></div>
<div class="problem"></div>
<div class="problem"></div>  
</div>

最新更新