Javascript innerhtml显示

时间:2015-07-22 23:11:47

标签: javascript html innerhtml

嗨我做了一个用于掷硬币的js脚本,当我按下按钮启动时没有出现任何内容

    <script>
    var coin = Math.random();
    if(coin <= 0.5){
     return "H";
    }
    else{
    return "T";
    }

    var coinFlip = function(){
      document.getElementById("flip").innerHTML = coin;
    }
  </script>

这是按钮

<button onClick="coinFlip()">Flip</button>

感谢您阅读

1 个答案:

答案 0 :(得分:0)

硬币是一个随机数,回报并没有按照你的想法行事。

&#13;
&#13;
var coinFlip = function() {
  var coin,
    chance = Math.random();
  if (chance <= 0.5) {
    coin = "H";
  } else {
    coin = "T";
  }
  document.getElementById("flip").innerHTML = coin;
}

document.getElementById("btn").addEventListener("click", coinFlip);
&#13;
<div id="flip"></div>
<button id="btn">Flip</button>
&#13;
&#13;
&#13;