简体   繁体   中英

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. I am sure it is something really simple but I can not see it.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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