将HTML元素转换为返回NaN Javascript的Int



我正在尝试制作一个玩家健康计数器,但我仍在返回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的属性。所以当你读h2value时,你得到undefined,当你把undefined传给parseInt时,你获得NaN

 var player1HP = parseInt(document.getElementById("play1HP").innerHTML);

h2元素没有value属性,因此parseInt将返回NaN。您需要使用innerHTMLtextContent来获取值。此外,您还需要使用变量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;
}

最新更新