我正在尝试从HTML中的img中获取ID,并将这些ID(与我创建的js对象相对应)作为参数传递,然后在函数中访问这些对象的某些属性。
我尝试了各种不同的方法来选择子元素的id,但是在运行该函数时我仍然会得到“ undefined”,因为出于某种原因,将id作为参数传递不允许我执行以下操作:访问该对象的键。我猜这是因为id是一个字符串,而“ string” .key将不起作用。但是,如果是这种情况,是否有办法动态获取对象名称并将其作为参数传递?我还很新,所以如果我不能很好地解释自己,我表示歉意,希望代码更有意义。
let peas = {
name : "peas",
attack : 5,
health : 100,
counterAttack : 10,
enemy : false
};
let broccoli = {
name : "broccoli",
attack : 5,
health : 100,
counterAttack : 10,
enemy : false
};
function battleFunction(player, computer) {
//increments playerAttack
newAttack += player.attack;
player.health -= computer.counterAttack;
//deducts attack from computer HP
if (newAttack > player.attack) {
computer.health -= newAttack;
console.log(computer.health);
} else {
computer.health -= player.attack;
console.log(computer.health);
}
if (computer.health <= 0) {
defeatedEnemies++
}
if (defeatedEnemies >= 4) {
alert("You won!");
resetGame();
}
};
$("#fightBtn").click( () => {
battleFunction($("#playerDiv").children("img").attr("id"), $("#computerDiv").children("img").attr("id"));
});
我希望$("#playerDiv").children("img").attr("id")
返回“豌豆”,并且确实如此。然后,我希望函数中的player.attack像peas.attack一样工作。
如果有一个更好的方法可以做到这一点,那么我就会不知所措。
非常感谢您的帮助!
答案 0 :(得分:1)
这是一个答案:'如何将字符串转换为变量名?'
首先,您需要一个周围的物体。您可以使用Window对象,但不建议这样做。因此,您可以在这里看到我创建了一个简单的类,其中包含两个表示您的对象的属性,“ sullivan”是播放器,“ johnson”是计算机。
由于Controller类包装了这些变量名,所以我们可以使用从类创建的对象,并使用[]
括号表示法来访问如下属性:
ctrl[player]
然后,如果“玩家”指向字符串“ sullivan”,则可以访问sullivan的属性。
您可以看到,在班级内部,我们可以使用this
关键字来访问它们:
this[player]
我已经在下面完成了您的示例。如果您有任何问题,请告诉我:
class Controller {
constructor() {
this.newAttack = 0;
this.defeatedEnemies = 0;
this.sullivan = {
name: "Sullivan",
attack: 4,
health: 10
};
this.johnson = {
name: "Johnson",
counterAttack: 8,
health: 10
};
}
battleFunction(player, computer) {
//increments playerAttack
this.newAttack += this[player].attack;
this[player].health -= this[computer].counterAttack;
//deducts attack from computer HP
if (this.newAttack > this[player].attack) {
this[computer].health -= this.newAttack;
console.log(this[computer].health);
} else {
this[computer].health -= this[player].attack;
console.log(this[computer].health);
}
if (this[computer].health <= 0) {
this.defeatedEnemies++
}
if (this.defeatedEnemies >= 4) {
alert("You won!");
//resetGame();
}
};
}
const ctrl = new Controller();
$("#fightBtn").click(() => {
ctrl.battleFunction($("#playerDiv").children("img").attr("id"), $("#computerDiv").children("img").attr("id"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="fightBtn">Fight!</button>
<div id="playerDiv"><img id="sullivan"></div>
<div id="computerDiv"><img id="johnson"></div>