我有一个可以正常工作的函数,但是我想使其可重用,以便以后在其他项目中使用。当我尝试修改代码以接受参数时 而不是在函数中声明所有内容。这是我当前的工作代码……
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);
这是我要使我的代码可重用的工作。.
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));
对于第二段代码,我没有任何反应,也没有console.logs,文本始终保持黑色。我确信这确实很简单,但我看不到。
答案 0 :(得分:1)
您正在将函数的结果传递给addEventListener
而不是函数:
window.addEventListener("load", function() { changeColourDesired(textToColour, textColours); });