gpt4 book ai didi

javascript - 将 id 从函数传递给 html 按钮

转载 作者:行者123 更新时间:2023-12-03 09:26:19 25 4
gpt4 key购买 nike

这是我的旧代码,违反了“不要重复自己”的规则。我想修改它,所以我只使用一个函数。

我当前的代码:

//initialize player data
var player = {
tech: 0,
energy: 0,
};

//initialize tech building data
var engineer = {
name: "Engineer",
owned: 0,
cost: 5,
generates: 1
};

var android = {
name: "Android",
owned: 0,
cost: 10,
generates: 5
};

//购买函数

function addEngi(amount){
var cost = amount * engineer.cost;
if cost <= player.tech{
engineer.owned += amount;
player.tech -= cost ;
}
else {
console.log("Not enough resources");
}
document.getElementById("Engineers").innerHTML = engineer.owned;
}

function addAndro(amount){
var cost = amount * android.cost;
if cost <= player.tech{
android.owned += amount;
player.tech -= cost ;
}
else {
console.log("Not enough resources");
}
document.getElementById("Androids").innerHTML = android.owned;
}

Engineers: <span id="Engineers"></span><br />
<button type="button" class="btn btn-default" onclick="addEngi(1)">Buy 1</button>
<button type="button" class="btn btn-default" onclick="addEngi(5)">Buy 5</button>

Androids: <span id="Androids"></span><br />
<button type="button" class="btn btn-default" onclick="addAndro(1)">Buy 1</button>
<button type="button" class="btn btn-default" onclick="addAndro(5)">Buy 5</button>

如您所见,我需要为添加到游戏原型(prototype)中的每个单位重复购买功能。

我的目标和想法是做这样的事情:

function testAdd(amount, building, id){
var cost = amount * building.cost;
if (cost <= player.tech){
building.owned += amount;
player.tech -= cost;
document.getElementById(id).innerHTML = building.owned;
}
else {
console.log("Not enough resources");
}

}

<button type="button" class="btn btn-default" onclick="testAdd(1, engineer, "Engineers")">Buy 1</button>

除了我需要传递 id 的部分之外,一切似乎都工作正常。

最佳答案

尝试在 id 周围使用单引号:

<button type="button" class="btn btn-default" onclick="testAdd(1, engineer, 'Engineers')">Buy 1</button>

关于javascript - 将 id 从函数传递给 html 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31655135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com