我有可以工作的代码,但想知道是否有一种方法可以将其与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>
最佳答案
这对你有用吗?
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;
}
}
关于javascript - javascript使用输入类型添加和减去复选框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33725846/