【问题标题】:Javascript Submit Button Random Coin TossJavascript 提交按钮 随机抛硬币
【发布时间】:2018-10-17 07:12:22
【问题描述】:

希望这是一个快速修复。我有一个可以正常工作的抛硬币生成器(耶!)但我希望能够多次点击翻转按钮并运行该功能,而无需重新加载和刷新页面。

var randomNumber = Math.floor(Math.random() * 2) + 1;

document.getElementById("flip").onclick = function(junction){
  if(randomNumber == 1){
    document.getElementById("response").innerHTML = "Heads!";
  } else {
    document.getElementById("response").innerHTML = "Tails!";
  }
}
<!DOCTYPE html>
<html>
<head>
    <title>Heads or Tails</title>
</head>
<body>
    <h1>Will it be heads or tails?</h1>
    <h3 id="response"></h3>
    <button id="flip" type="button">Let's Flip!</button>
</body>
<script src="app.js"></script>
</html>

【问题讨论】:

  • 只需删除 document.getelement... 并用函数 junction(){} 替换它。它会起作用的!

标签: javascript html random coin-flipping


【解决方案1】:
function junction (){
var randomNumber=Math.floor(Math.random()*2)+1;
if(randomNumber==1){
  document.getElementById("response").innerHTML ="Heads!";
  }
 else {
 document.getElementById("response").innerHTML ="Tails!";
 }
}

在 javascript 中声明一个函数并使用 onclick 属性调用它。

【讨论】:

    【解决方案2】:

    看看那个代码sn-p,它有效!

    function junction(){
      var randomNumber = Math.floor(Math.random() * 2) + 1;
      
      if(randomNumber == 1){
        document.getElementById("response").innerHTML = "Heads!";
      } else {
        document.getElementById("response").innerHTML = "Tails!";
      }
    }
    <!DOCTYPE html>
    <html>
    <head>
    
        <title>Guess the Number!</title>
    </head>
    <body>
        <h1>Guess the Number!</h1>
        <p>See if you can guess the number between 1 and 50</p>
        <label for="guess"> Enter Your Guess </label>
        <input type="text" id="guess"><br>
        <button id="submit" onclick="junction();">Submit Guess</button>
        <p id="response"></p>
    </body>
    </html>

    【讨论】:

    • 我复制了错误的 HTML,但将您的建议应用到了正确的文件中,效果非常好!谢谢!
    【解决方案3】:

    嘿,您可能需要进行一些更改!在 javascript 中,您在这里使用 id flip document.getElementById("flip").onclick =function(junction){ 但您的代码没有任何带有 id flip 的元素! 编辑并赶上进度。

    【讨论】:

    • 啊!我昨晚发帖时复制了错误的 HTML!现在就来看看吧!
    猜你喜欢
    • 2018-07-27
    • 1970-01-01
    • 2012-10-23
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多