我有这个项目的所有组件,除了一个类方法显示数组中的前两个图像(Pokeball和默认eevee),然后从数组中随机选择另一个图像(eevee进化),然后停止。
请耐心点,我是新手。
class Pokemon {
constructor() {
this.listOfCharmander = [
"./images/pokeball.png",
"./images/charmander/charmander0.png",
"./images/charmander/charmander1.png",
"./images/charmander/charmander2.png",
];
this.index = 0;
this.pokemon = document.createElement("img");
}
handleClick = () => {
if (this.index < 3) {
++this.index;
this.pokemon.src = this.listOfCharmander[this.index];
}
};
buildPokemon = () => {
this.pokemon.src = this.listOfCharmander[0];
this.pokemon.classList.add("pokemon");
this.pokemon.addEventListener("click", this.handleClick);
main.appendChild(this.pokemon);
};
}
const pokemon = new Pokemon();
const pokemon1 = new Pokemon();
pokemon.buildPokemon();
pokemon1.buildPokemon();
class Eevee {
constructor() {
this.eeveeEvolutions = [
"/images/pokeball.png",
"images/eevee/eevee0.png",
"images/eevee/eevee1.png",
"images/eevee/eevee2.png",
"images/eevee/eevee3.png",
"images/eevee/eevee4.png",
"images/eevee/eevee5.png",
"images/eevee/eevee6.png",
"images/eevee/eevee7.png",
"images/eevee/eevee8.png",
];
this.index = 0;
this.eevee = document.createElement("img");
}
handleClick = () => {
if (this.index < 9) {
++this.index;
this.eevee.src = this.eeveeEvolutions[this.index];
}
};
buildEevee = () => {
this.eevee.src = this.eeveeEvolutions[0];
this.eevee.classList.add("eevee");
this.eevee.addEventListener("click", this.handleClick);
main.appendChild(this.eevee);
};
}
const eevee = new Eevee();
const eevee1 = new Eevee();
eevee.buildEevee();
eevee1.buildEevee();
…如果我的问题不是很清楚,我很抱歉。我需要添加到我的handClick方法。一种方法显示第一张图像(Pokeball),然后是第二张图像(默认eevee),然后随机选择(包括保持不变,可能根本没有进化)从剩余的数组中再选择一个进化。
如果你总是需要数组中的前两个图像,那么你可以添加额外的属性到你的Eevee类来存储这些图像的路径,对于随机图像,你可以将此代码添加到你的handleClick()
handleClick = () => {
this.index=Math.floor(Math.random(2,9)*10)
this.eevee.src = this.eeveeEvolutions[this.index];
};