我的代码有效,但想知道是否有办法用JS循环压缩它?我试过了,但我遇到了麻烦。我正在尝试为我计划玩的游戏构建一个计算器网页。 "隐藏"是游戏中皮肤活动的素材项目。我预计会有几件物品。谢谢!
total = 0;
hide1 = 1;
hide2 = 1;
hide3 = 1;
function addUp(num, x) {
if (x == "hide1" && hide1 == 1) {
temp = document.theForm.ttl.value;
tempo = parseInt(temp);
numo = parseInt(num);
nwTemp = tempo + numo;
document.theForm.ttl.value = nwTemp;
hide1 = 0;
return hide1;
}
if (x == "hide1" && hide1 == 0) {
temp = document.theForm.ttl.value;
tempo = parseInt(temp);
numo = parseInt(num);
nwTemp = tempo - numo;
document.theForm.ttl.value = nwTemp;
hide1 = 1;
}
if (x == "hide2" && hide2 == 1) {
temp = document.theForm.ttl.value;
tempo = parseInt(temp);
numo = parseInt(num);
nwTemp = tempo + numo;
document.theForm.ttl.value = nwTemp;
hide2 = 0;
return hide2;
}
if (x == "hide2" && hide2 == 0) {
temp = document.theForm.ttl.value;
tempo = parseInt(temp);
numo = parseInt(num);
nwTemp = tempo - numo;
document.theForm.ttl.value = nwTemp;
hide2 = 1;
}
if (x == "hide3" && hide3 == 1) {
temp = document.theForm.ttl.value;
tempo = parseInt(temp);
numo = parseInt(num);
nwTemp = tempo + numo;
document.theForm.ttl.value = nwTemp;
hide3 = 0;
return hide3;
}
if (x == "hide3" && hide3 == 0) {
temp = document.theForm.ttl.value;
tempo = parseInt(temp);
numo = parseInt(num);
nwTemp = tempo - numo;
document.theForm.ttl.value = nwTemp;
hide3 = 1;
}
}

<form name="theForm" style="display:block;border:1px">
<div id="t1" style="display:none;">
<input type="checkbox" onclick="addUp(4, 'hide1')">
Beginner's Leather Hood
<br/>
<input type="checkbox" onClick="addUp(8, 'hide2')">
Beginner's Leather Armor
<br/>
<input type="checkbox" onClick="addUp(4, 'hide3')">
Beginner's Leather Shoes
<br/>
</div>
<div id="t2" style="display:none;">
<input type="checkbox" onclick="addUp(8, 'hide4')">
Novice's Leather Hood
<br/>
<input type="checkbox" onClick="addUp(16, 'hide5')">
Novice's Leather Armor
<br/>
<input type="checkbox" onClick="addUp(8, 'hide6')">
Novice's Leather Shoes
<br/>
</div>
Total Number:
<input type="text" name="ttl" value=0>
</form>
&#13;
答案 0 :(得分:1)
我会考虑查看data-* attributes和event listeners。您可以为每个复选框的值设置数据属性,然后为复选框的更改事件提供事件侦听器。
答案 1 :(得分:0)
这对你有用吗?
total = 0;
var hide = [];
hide[1] = 1;
hide[2] = 1;
hide[3] = 1;
function addUp(num, x) {
var index = parseInt(x.replace("hide",""));
if(hide[index] == 1)
{
temp = document.theForm.ttl.value;
tempo = parseInt(temp);
numo = parseInt(num);
nwTemp = tempo + numo;
document.theForm.ttl.value = nwTemp;
hide[index] = 0;
return hide[index];
}
else if(hide[index] == 0)
{
temp = document.theForm.ttl.value;
tempo = parseInt(temp);
numo = parseInt(num);
nwTemp = tempo - numo;
document.theForm.ttl.value = nwTemp;
hide[index] = 1;
}
}