简体   繁体   English

如何使用Java脚本为游戏创建重启按钮

[英]How to create a restart button for a game in Java Script

I am new to JavaScript. 我是JavaScript新手。

I have been creating a game- which includes the number of goes a person has had to guess a random number. 我一直在创造一个游戏-包括一个人不得不猜测一个随机数的走数。

I have created the button however I am having problems trying to restart the game - making a new random number to be generated and the number of goes to return to 0 我已经创建了按钮,但是尝试重新启动游戏时遇到了问题-生成了一个新的随机数,返回的次数变为0

var randomno =Math.floor(Math.random() * 100 ) + 1;
    let restart = document.getElementById("restart");
    function restartGame(){    
        num();
    }
}
restartGame();

This is only a small snippet of my code. 这只是我的代码的一小段。

You want to assign a click handler to your restart element which is missing from the OP code snippet... https://developer.mozilla.org/en-US/docs/Web/Events/click 您想为您的重启元素分配一个点击处理程序,而该重启处理程序是OP代码片段中缺少的... https://developer.mozilla.org/zh-CN/docs/Web/Events/click

  document.getElementById("restart").addEventListener("click", function() {
    // restart the game
  });

A quick fix which may or not be optimal for you is to simply refresh the page. 一个快速的解决方法(可能不适合您)是简单地刷新页面。 Use something like 'location.reload();' 使用类似“ location.reload();”的方法 to do this. 去做这个。

As I could understand you only need to re-assign some variables. 据我了解,您只需要重新分配一些变量。

To do that, just put the variable name followed by the equals sign and the new value you want it. 为此,只需在变量名后加上等号和所需的新值即可。

var randomno = Math.floor(Math.random() * 100 ) + 1;
randomno = Math.floor(Math.random() * 100 ) + 1;

The second line the variable is being re-assigned. 正在重新分配变量的第二行。

If you also have a problem of binding an action for your button to call a javascript event(in your case restart the game), please read this article: https://developer.mozilla.org/en-US/docs/Web/Events/click 如果您还存在为按钮绑定动作来调用javascript事件的问题(在您的情况下,请重新启动游戏),请阅读此文章: https : //developer.mozilla.org/en-US/docs/Web/事件/点击

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM