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

时间:2015-11-14 10:01:06

标签: javascript html counter nan parseint

我正在尝试制作一个玩家健康计数器,但我仍然会让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;
}

3 个答案:

答案 0 :(得分:1)

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>

答案 1 :(得分:1)

您需要innerHTML而不是value。发生这种情况是因为h2元素没有名为value的属性。因此,当您阅读value h2时,undefined获得undefined,当您将parseInt传递给NaN时,您会获得 var player1HP = parseInt(document.getElementById("play1HP").innerHTML);

{{1}}

答案 2 :(得分:0)

你最好使用变量来存储健康值:

<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;
}