在for循环中将onClick应用于函数数组(每个按钮上执行的每个函数单击)

时间:2015-07-02 13:43:21

标签: javascript jquery loops

你好stackoverflow的人!

我希望在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>

`

1 个答案:

答案 0 :(得分:0)

<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>