我试图将函数参数传递给变量(如果可能)以减少代码重复性,并嵌套if语句/ switch语句。通过研究,我发现getElementById引用需要放在引号中以显示为id。主要问题是,我可以将参数传递给变量名吗?
<body>
<div class="contain">
<h3 id="red">0</h3>
<h3 id="green">0</h3>
<h3 id="blue">0</h3>
<button onClick="player_one.addResource(4,green)">Add Green</button>
<button onClick="player_one.addResource(3,red)">Add Red</button>
<button onClick="player_one.addResource(7,blue)">Add Blue</button>
</div>
<script>
var redResource = 0;
var greenResource = 0;
var blueResource = 0;
var player_one = {
addResource: function(num,color){
(color)Resource += num
document.getElementById(color).innerHTML =((color)Resource);
}
}
</script>
</body>
--------------------------------------------------------------------
--------------------------------------------------------------------
//with a different approach, I still have an issue
var player_one = {
addResource: function(num,color){
player_one.color += num
document.getElementById(color).innerHTML = (player_one.color);
},
red: 0,
green: 0,
blue: 0
}
答案 0 :(得分:3)
您可以使用Object来代替变量:
var resources = {
red: 0,
green: 0,
blue: 0
};
var player_one = {
addResource: function(num, color) {
resources[color] += num;
document.getElementById(color).innerHTML = resources[color];
}
};
答案 1 :(得分:0)
最好使用对象,而不要花一些技巧
var player_one = {
addResource: function(num,color){
player_one[color] += num
document.getElementById(color).innerHTML = (player_one[color]);
},
red: 0,
green: 0,
blue: 0
}
// console.log(document.getElementById('green'))
<div class="contain">
<h3 id="red">0</h3>
<h3 id="green">0</h3>
<h3 id="blue">0</h3>
<button onClick="player_one.addResource(4,'green')">Add Green</button>
<button onClick="player_one.addResource(3,'red')">Add Red</button>
<button onClick="player_one.addResource(7,'blue')">Add Blue</button>
</div>
您所缺少的是使用字符串参数..而不是func(3, 'red')
来调用函数。
,并且使用JavaScript func(3, red)
而不是player_one[color]
答案 2 :(得分:0)
这是不好的编码,但这是您的答案:
_headerKey
var
redResource = 0,
greenResource = 0,
blueResource = 0
;
var player_one = {
addResource: function(num,color){
window[color+'Resource'] += num;
document.getElementById(color).innerHTML = window[color+'Resource'];
}
}
#red { color:red }
#green { color:green }
#blue { color:blue }