而不是39500输出我获得500.有人可以帮助我,我想如果gw达到0,墙上应该没有-500。
我使用了我的代码,但它无效。 HTML
<li><b>Infantry: </b><span id="gw">40000</span></li>
<p class="fort"><b>Fort: </b><span id="wall">1000</span></p>
<button class="troops" onclick="send()">SEND TROOPS</button>
JS
function send(){
var a = document.getElementById('gw').innerHTML;
var b = 500;
var c = a-b;
var label = document.getElementById('wall');
label.innerHTML = parseInt(label.innerHTML) - b;
var label = document.getElementById('gw');
label.innerHTML = parseInt(label.innerHTML) - c;
}
答案 0 :(得分:1)
您的主要问题是您正在var c = a-b;
,b
是一个号码,但a
是一个字符串(Element.innerHTML
) - 没有parseInt(value, radix)
在那个价值......那里还有其他的数学减法混淆...
<强>相反:强>
// Helper function to set to 0 a value lower than 0
function zeroMin(val) {
return parseInt(val, 10) < 0 ? 0 : val;
}
function send() {
var EL_gw = document.getElementById('gw'),
EL_wa = document.getElementById('wall'),
gw = parseInt(EL_gw.innerHTML, 10),
wa = parseInt(EL_wa.innerHTML, 10),
hitVal = 500;
// Subtract
gw -= hitVal;
wa -= hitVal;
// fix to 0
gw = zeroMin(gw);
wa = zeroMin(wa);
EL_gw.innerHTML = gw;
EL_wa.innerHTML = wa;
}
&#13;
<b>Infantry:</b> <span id="gw">40000</span> <br>
<b>Fort:</b> <span id="wall">1000</span> <br>
<button class="troops" onclick="send()">SEND TROOPS</button>
&#13;
如果您希望在任何值达到0
时停止任何进一步的操作
function send() {
var EL_gw = document.getElementById('gw'),
EL_wa = document.getElementById('wall'),
gw = parseInt(EL_gw.innerHTML, 10),
wa = parseInt(EL_wa.innerHTML, 10),
hitVal = 500;
if (gw <= 0 || wa <= 0) return; // Do nothing if any is <= 0
// else...
gw -= hitVal;
wa -= hitVal;
EL_gw.innerHTML = gw;
EL_wa.innerHTML = wa;
}
&#13;
<b>Infantry:</b> <span id="gw">40000</span>
(will stop decreasing if FORT energy is 0 and vice-versa)<br>
<b>Fort:</b> <span id="wall">1000</span> <br>
<button class="troops" onclick="send()">SEND TROOPS</button>
&#13;
答案 1 :(得分:0)
您的代码运行正常,只是您在这里犯了错误
<span class= id="wall">1000</span></p>
如果您不需要,请删除class=
或添加课程。
关于价值检查员的询问。我创建了一个代码片段来帮助您。
function send(){
var labelWall = document.getElementById('wall');
var labelGW = document.getElementById('gw');
var wallValue = parseInt(labelWall.innerHTML, 10);
var GWValue = parseInt(labelGW.innerHTML, 10);
var b = 500;
if(wallValue > 0 && GWValue > 0) {
labelGW.innerHTML = GWValue - b;
labelWall.innerHTML = wallValue - b;
}
}