嗨,如何多次使用一个方法而不在 JavaScript 中重复和创建另一个方法。因为我所做的是我创建了一个具有相同字段和代码的方法,但唯一的区别是 id。我需要每个方法的一个参数,即 id。
function enemyGet() {
new enemyMove2()
new enemyMove()
new enemyMove3()
}
function enemyMove2() {
var enemyimage = document.getElementById("enemy");
var leftenemy = parseInt(enemyimage.style.left);
var topenemy = parseInt(enemyimage.style.top);
var time = setTimeout("enemyMove2()", 20)
if (leftenemy < leftplayer) {
leftenemy = leftenemy + 5;
}
if (leftenemy > leftplayer) {
leftenemy = leftenemy - 5;
}
if (topenemy < topplayer) {
topenemy = topenemy + 5;
}
if (topenemy > topplayer) {
topenemy = topenemy - 5;
}
enemyimage.style.left = leftenemy + "px";
enemyimage.style.top = topenemy + "px";
var hit_list = $("#x").collision(".lollol");
hit_list.remove();
}
function enemyMove() {
var enemyimage = document.getElementById("enemy2");
var leftenemy = parseInt(enemyimage.style.left);
var topenemy = parseInt(enemyimage.style.top);
var time = setTimeout("enemyMove()", 20)
if (leftenemy < leftplayer) {
leftenemy = leftenemy + 5;
}
if (leftenemy > leftplayer) {
leftenemy = leftenemy - 5;
}
if (topenemy < topplayer) {
topenemy = topenemy + 5;
}
if (topenemy > topplayer) {
topenemy = topenemy - 5;
}
enemyimage.style.left = leftenemy + "px";
enemyimage.style.top = topenemy + "px";
var hit_list = $("#x").collision(".lollol");
hit_list.remove();
}
function enemyMove3() {
var enemyimage = document.getElementById("enemy3");
var leftenemy = parseInt(enemyimage.style.left);
var topenemy = parseInt(enemyimage.style.top);
var time = setTimeout("enemyMove3()", 20)
if (leftenemy < leftplayer) {
leftenemy = leftenemy + 5;
}
if (leftenemy > leftplayer) {
leftenemy = leftenemy - 5;
}
if (topenemy < topplayer) {
topenemy = topenemy + 5;
}
if (topenemy > topplayer) {
topenemy = topenemy - 5;
}
enemyimage.style.left = leftenemy + "px";
enemyimage.style.top = topenemy + "px";
var hit_list = $("#x").collision(".lollol");
hit_list.remove();
}