繁体   English   中英

如何循环遍历按钮数组,并且只有在用户单击数组中的下一个按钮时才继续循环

[英]How do I loop through an array of buttons and only continue looping if the user clicks the next button in the array

不确定这是否是正确的方法,但我在屏幕上生成了一组按钮,几秒钟后它会改变位置,我必须按照它们最初出现的顺序单击按钮。

以下是代码

 let arrayButtons = []; let goButton = document.getElementById("inputButton"); function Buttons(color, height, width, top, left, order) { this.order = order; this.btn = document.createElement("button"); this.btn.style.backgroundColor = color; this.btn.style.height = height; this.btn.style.width = width; this.btn.style.position = "absolute"; document.body.appendChild(this.btn); this.setLocation = function(top, left) { this.btn.style.top = top; this.btn.style.left = left; }; this.setLocation(top, left); } function createButtons(numOfButtons) { console.log(numOfButtons); let color; let heightVal; let widthVal; let top; let left; let currentButton; for (let i = 0; i < numOfButtons; i++) { color = "#" + genRandomColor(); heightVal = "60px"; widthVal = "120px"; let x = window.innerWidth - 100; let y = window.innerHeight - 100; top = 90 + "px"; left = i * 120 + "px"; currentButton = new Buttons(color, heightVal, widthVal, top, left, i); arrayButtons.push(currentButton); } } function genRandomColor() { let randomColor = Math.floor(Math.random() * 16777215).toString(16); return randomColor; } function change() { setTimeout(function() { let x = window.innerWidth - 100; let y = window.innerHeight - 200; for (let i = 0; i < arrayButtons.length; i++) { randomX = Math.floor(Math.random() * x + 50); randomY = Math.floor(Math.random() * y + 50); arrayButtons[i].setLocation( randomX + 'px', randomY + 'px'); } }, 5000); } function isValid(range) { range = document.getElementById("textField").value; if (range < 2 || range > 10) { return false; } else { return true; } } // idea.. if the user clicks on the button in the order of the array it works // for the hint, just make the value equal to the index number + 1 function clickHandler() { let minMax = isValid(); if (minMax == true) { createButtons(document.getElementById("textField").value); change(); } else { window.alert("Must be between 2 and 10"); } } goButton.onclick = clickHandler;
 <p>How Many Buttons To Create?</p> <input id="textField" type="text"> <button type="button" id="inputButton">Go!</button> <br> <br>

HTML

<button class="buttonClass">1</button>

JS

let btns = document.querySelectorAll(".buttonClass");
let currentBtn = 0;
btns.forEach(function(btn, crtIndex){
    btn.onclick = function(){
        if(currentBtn === crtIndex){
            currentBtn++;
            console.log("correct");
        }
    };
});

暂无
暂无

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

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