我是javascript的新手,我需要一些帮助。 我想制作一个收集木头/石头的按钮,当它被按下时我希望它减少耐力1.我制作了一个代码,但它不起作用。
<div class="menu">
<p class="ing">Stamina:<p id="stamina">20</p></p>
<button onclick="collect_wood()" class="button">Collect Wood</button><p class="ing">Wood:<p id="wood">0</p> </p>
<button onclick="collect_stone(stamina)" class="button2">Collect Stone</button><p class="ing2">Stone:<p id="stone">0</p> </p>
</div>
<script>
wood=0;
stone=0;
stamina=20;
function collect_wood() {
stamina = stamina - 1;
wood=wood+1;
document.getElementById("wood").innerHTML = wood;
}
function collect_stone(stamina) {
stamina = stamina - 1;
stone=stone+1;
document.getElementById("stone").innerHTML = stone;
}
document.getElementById("stamina").innerHTML = stamina;
</script>
答案 0 :(得分:0)
答案 1 :(得分:0)
你有90%!看起来你正在做的一切正确,但你没有更新耐力dom对象,除了在初始运行。您只需要在函数内移动更新stamina对象的innterHTML。这样的事情:
`
wood=0;
stone=0;
stamina=20;
function collect_wood() {
stamina = stamina - 1;
wood=wood+1;
document.getElementById("wood").innerHTML = wood;
//Update each time!
document.getElementById("stamina").innerHTML = stamina;
}
function collect_stone(stamina) {
stamina = stamina - 1;
stone=stone+1;
document.getElementById("stone").innerHTML = stone;
//Update each time!
document.getElementById("stamina").innerHTML = stamina;
}
`
祝你好运,欢迎来到html和javascript世界!
答案 2 :(得分:0)
点击stamina
计数时,您的wood
变量正在更新,但在stone
计数时,您正在创建一个产生问题的参数。删除它将起作用。
每次点击后你都应该更新innerHTML
耐力。
喜欢吼叫
function collect_wood() {
stamina = stamina - 1;
wood=wood+1;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stamina").innerHTML = stamina;
}
function collect_stone() {
stamina = stamina - 1;
stone=stone+1;
document.getElementById("stone").innerHTML = stone;
document.getElementById("stamina").innerHTML = stamina;
}
不要将参数传递给collect_stone
函数
<button onclick="collect_stone()" class="button2">Collect Stone</button>
答案 3 :(得分:0)
请确保您正确引用所有内容。在您的函数中使用console.log以确保它们被触发等等。
<div class="menu">
<p class="ing">Stamina:
<p id="stamina">20</p>
</p>
<button onclick="collect_wood()" class="button">Collect Wood</button>
<p class="ing">Wood:
<p id="wood">0</p>
</p>
<button onclick="collect_stone()" class="button2">Collect Stone</button>
<p class="ing2">Stone:
<p id="stone">0</p>
</p>
</div>
<script>
wood = 0;
stone = 0;
stamina = 20;
function collect_wood() {
stamina--;
wood++;
document.getElementById("wood").innerHTML = wood;
update_stamina();
}
function collect_stone() {
stamina--;
stone++;
document.getElementById("stone").innerHTML = stone;
update_stamina();
}
function update_stamina() {
document.getElementById("stamina").innerHTML = stamina;
}
</script>
答案 4 :(得分:0)
我尝试了你的代码,但在页面加载时调用了一次。 为什么不能更新函数内的'stamina'变量值?
function collect_stone(stamina) {
//alert(stamina);
stamina = stamina - 1;
stone=stone+1;
document.getElementById("stone").innerHTML = stone;
}