如何更新显示的变量

时间:2017-06-22 01:34:00

标签: javascript html

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<script type="text/javascript">
var tic;
tic = 0;
</script>

<script type="text/javascript">
document.write(tic);
</script>




<script>
var ongngic;
ongngic = 1;
</script>

<button onclick="alert(tic=tic+ongngic);">Ice Cream</button>
</body>
</html>

我用document.write显示了变量“tic”。我不确定如何通过单击id =“b1”按钮来更改它。有人能帮助我吗?

2 个答案:

答案 0 :(得分:1)

您需要更新变量以及DOM:

  • 请勿使用document.write()
  • 使用DOM元素并修改.innerHTML
  • 单独的HTML和JavaScript。

var tic;
tic = 0;
var ongngic;
ongngic = 1;
document.getElementById("output").innerHTML = tic;
function perform() {
  tic= tic + ongngic;
  document.getElementById("output").innerHTML = tic;
}
<div id="output"></div>
<button onclick="perform();" type="button">Ice Cream</button>

答案 1 :(得分:0)

您需要将值绑定到HTML,如下所示。

<body>
  <div id="tic_div"></div>
    <button onclick="add()">Ice Cream</button>  
    <script type="text/javascript">
      var tic = 0;
      var ongngic = 1;

      document.getElementById("tic_div").innerHTML = tic;

      function add(){
        tic=tic+ongngic;
        document.getElementById("tic_div").innerHTML = tic;
      }
  </script>
</body>