对For循环中的函数数组应用onClick(每次单击按钮时执行的每个函数)

Applying onClick to Function Array in a For Loop (Each Function executed on each Button Click)

本文关键字:函数 单击 按钮 执行 onClick 循环 For 数组 应用      更新时间:2023-09-26

斯塔克夫弗洛的人们好!

我希望使用Javascript中的一个按钮按顺序(一个接一个(执行一系列函数。点击按钮,而不是一次全部执行。(请参阅下面的功能显示(

目前,所有功能都同时执行。有人能帮忙吗!?我希望能够点击按钮,让每个彩色方块一个接一个地出现在屏幕上,每次点击按钮。

function red () {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#red";
ctx.fillRect(20,60,23,23);
}
function blue() {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#blue";
ctx.fillRect(20,100,23,23);
}
function green() {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#green";
ctx.fillRect(20,20,23,23);
}

function functionarray() {
var array_of_functions = [
green,
red,
blue, 
]

for (i = 0; i < array_of_functions.length; i++) {
array_of_functions[i]();
}
}
function displayNext() {
var array_of_functions = [
green,
red,
blue, 
]
for (i = 0; i < array_of_functions.length; i++) {
array_of_functions[i].onclick = array_of_functions[i]();
//array_of_functions[i].onclick();
}
}
<p><button type="button" onclick="displayNext()">On Click, next                 colour</button></p>
</html>

`

<html>
<head>
    <title></title>
</head>
<body>
    <p>
        <button type="button" id="myID">next color</button>
    </p>
<script>
var canvas = document.getElementById("myCanvas"),
    ctx = canvas.getContext("2d"),
    red = function red() {
        ctx.fillStyle="#red";
        ctx.fillRect(20,60,23,23);
    },
    blue = function blue() {
        ctx.fillStyle="#blue";
        ctx.fillRect(20,100,23,23);
    },
    green = function green() {
        ctx.fillStyle="#green";
        ctx.fillRect(20,20,23,23);
    },
    lastCall = 0,
    array_of_functions = [green, red, blue],
    displayNext = function displayNext() {
        array_of_functions[lastCall]();
        lastCall += 1;
    };
document.getElementById('myID').addEventListener('click', displayNext);
</script>
</body>
</html>