我正在尝试制作一个玩家健康计数器,但我仍在返回NaN。。帮助
这是我的HTML
<!--player 1 hp-->
<div class="row">
<div class="col-sm-6 col-md-6 col-xs-12 col-lg-6">
<h2 class="text-center" id="play1HP">0</h2>
<button onclick="healthCountUp1()">+1</button>
</div>
和我的JavaScript
function healthCountUp1(){
var player1HP = parseInt(document.getElementById("play1HP").value);
var add = player1HP + 1;
document.getElementById("play1HP").innerHTML = player1HP;
}
您需要innerHTML
而不是value
。之所以发生这种情况,是因为h2
元素没有名为value
的属性。所以当你读h2
的value
时,你得到undefined
,当你把undefined
传给parseInt
时,你获得NaN
。
var player1HP = parseInt(document.getElementById("play1HP").innerHTML);
h2
元素没有value
属性,因此parseInt
将返回NaN
。您需要使用innerHTML
或textContent
来获取值。此外,您还需要使用变量add
进行更新。
function healthCountUp1() {
var player1HP = parseInt(document.getElementById("play1HP").innerHTML);
var add = player1HP + 1;
document.getElementById("play1HP").innerHTML = add;
}
<div class="col-sm-6 col-md-6 col-xs-12 col-lg-6">
<h2 class="text-center" id="play1HP">0</h2>
<button onclick="healthCountUp1()">+1</button>
</div>
function healthCountUp1() {
var player1HP = parseInt(document.getElementById("play1HP").textContent);
var add = player1HP + 1;
document.getElementById("play1HP").textContent = add;
}
<div class="col-sm-6 col-md-6 col-xs-12 col-lg-6">
<h2 class="text-center" id="play1HP">0</h2>
<button onclick="healthCountUp1()">+1</button>
</div>
您最好将变量存储在:中
<div class="row">
<div class="col-sm-6 col-md-6 col-xs-12 col-lg-6">
<h2 class="text-center" id="play1HP">0</h2>
<button onclick="healthCountUp1()">+1</button>
</div>
javascript:
var health = 0;
function healthCountUp1(){
health++;
document.getElementById("play1HP").innerHTML = health;
}