将id传递给函数中的html按钮

时间:2015-07-27 13:57:53

标签: javascript function button

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

我目前的代码:

//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>

正如您所看到的,我需要为我添加到游戏原型中的每个单元重复购买功能。

我的目标和想法是制作这样的东西:

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的部分外,一切似乎都能正常工作。

1 个答案:

答案 0 :(得分:1)

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

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