简体   繁体   English

需要帮助创建带有 for 循环的 html 元素

[英]need help creating html elements with a for loop

I am trying to create inputs in my html and am using a for loop to generate a random amount every time a button is clicked.我正在尝试在我的 html 中创建输入,并且每次单击按钮时都使用 for 循环生成随机量。 I click the button, the console prints out the random number but only one input is generated.我单击按钮,控制台打印出随机数,但只生成一个输入。 It is even printing out the correct number of console.logs , just not the inputs.它甚至打印出正确数量的console.logs ,而不是输入。 I am not sure why and would love any help.我不知道为什么,并希望得到任何帮助。

const generateRanNum = () => {
    let randomNumber = Math.floor(Math.random() * 20);
    return randomNumber
}



const generateInputs = (ranNum) => {
    const listItem = document.createElement('li');
    const input = document.createElement('input');
    for(let i = 1; i <= ranNum; i++){
        inputsList.appendChild(listItem);
        listItem.appendChild(input);
        console.log(ranNum)

    }


}

startButton.onclick = () => {
   const ranNum = generateRanNum()
    generateInputs(ranNum)
    // alert('clicked');
}


  • const input = document.createElement('input'); should go inside the for loop.应该 gofor循环内。

  • don't forget to insert your LI in the respective UL after the loop.不要忘记在循环后将您的 LI 插入相应的 UL 中。

const generateInputs = (ranNum) => {
    const listItem = document.createElement('li');

    for(let i = 1; i <= ranNum; i++){
        const input = document.createElement('input');
        listItem.appendChild(input);
    }

    inputsList.appendChild(listItem);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM