简体   繁体   English

使我的功能可重用

[英]Making my function reusable

I have a function that works how it is but I want to make it reusable so I can use it later on other projects. 我有一个可以正常工作的函数,但是我想使其可重用,以便以后在其他项目中使用。 When I try to modify the code to take arguments instead of declaring it all in the function nothing happens. 当我尝试修改代码以接受参数而不是在函数中全部声明时,什么也没有发生。 Here is my current working code...... 这是我当前的工作代码……

var textColours = ["red", "orange", "green", "blue", "purple"];

var textToColour = document.getElementsByClassName("menuItem");

var randomColour = "";

var coloursUsed = [];

function randomize(array) {
 return array[Math.floor(Math.random() * array.length)];
}


function changeColour() {
for(var i = 0; i < textToColour.length; i++) {
randomColour = randomize(textColours);
if(!coloursUsed.includes(randomColour)){
  console.log("dingaling aling!");
  textToColour[i].style.color =  randomColour;
  coloursUsed.push(textToColour[i].style.color);
} else {
  i--
  console.log("duplicate");
}
console.log(coloursUsed);
console.log(coloursUsed.includes(randomColour));
 }
}


window.addEventListener("load", changeColour);

Here is what I am trying to do to make my code reusable..... 这是我要做的使我的代码可重用的事情.....

function changeColourDesired(element, colourArray) {
for(var i = 0; i < element.length; i++) {
randomColour = randomize(colourArray);
if(!coloursUsed.includes(randomColour)){
  console.log("dingaling aling!");
  element[i].style.color =  randomColour;
  coloursUsed.push(element[i].style.color);
} else {
  i--
  console.log("duplicate");
}
console.log(coloursUsed);
console.log(coloursUsed.includes(randomColour));
}
}

window.addEventListener("load", changeColourDesired(textToColour,  textColours));

I am not getting any response for that second lot of code, no console.logs and the text just stays black. 对于第二段代码,我没有任何反应,也没有console.logs,文本仍然保持黑色。 I am sure it is something really simple but I can not see it. 我相信这确实很简单,但我看不到。

您正在将一个函数的结果而不是一个函数传递给addEventListener

window.addEventListener("load", function() { changeColourDesired(textToColour,  textColours); }); 

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

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