如何使此代码按预期工作?

时间:2018-04-09 16:01:40

标签: javascript function javascript-events

以下是任何人都可以查看的code

var button = document.querySelector("button");
var x = clickMagic();

function clickMagic(){
    var count = 0;
    var colorCode = ["#FF7F50", "#E9967A", "#FFA07A", "#FFD700", "#ADFF2F", "#98FB98", "#00FFFF", "#E0FFFF", "#AFEEEE", "#87CEEB", "#DDA0DD", "#FFB6C1", "#F5F5DC", "#FFEBCD", "#FFFFE0", "#DEB887", "#FFE4B5", "#FFDEAD", "#FAF0E6"];

    return document.getElementById("bodyEdit").style.backgroundColor = colorCode[count];

    if (count == numCount - 1) {
      console.log("End of Array and rotation");

    }
    count = count + 1;
}

button.addEventListener("click", x);

3 个答案:

答案 0 :(得分:2)

我认为这就是你要做的事情。

var button = document.querySelector("button");
var colorCode = ["#FF7F50", "#E9967A", "#FFA07A", "#FFD700", "#ADFF2F", "#98FB98", "#00FFFF", "#E0FFFF", "#AFEEEE", "#87CEEB", "#DDA0DD", "#FFB6C1", "#F5F5DC", "#FFEBCD", "#FFFFE0", "#DEB887", "#FFE4B5", "#FFDEAD", "#FAF0E6"];

var count = 0;

function clickMagic(){
  document.getElementById("bodyEdit").style.backgroundColor = colorCode[count];
  count++;
  if(count >= colorCode.length){
      console.log("End of Array and rotation");
      count = 0;
  }
}

button.addEventListener("click", clickMagic);

https://codepen.io/anon/pen/LdMaZq

答案 1 :(得分:1)

如果要在单击按钮时调用clickMagic,请按照这种方式编写

button.addEventListener("click", clickMagic)

答案 2 :(得分:1)

实际上你在这里做的是: var x = clickMagic(); 分配函数clickMagic的返回值,因此X将是未定义的(因为我没有看到任何返回)并且你也无法调用它(因为它是一个已经被触发的函数)

您应该将代码更改为: var x = clickMagic; button.addEventListener("click", x); //this will trigger the function when clicking the button

或采用其他方法: button.addEventListener("click", clickMagic); 问候。