获取无线电值以使用Javascript进行页面传输

时间:2013-12-14 03:35:04

标签: javascript html

我正在尝试构建一个非常简单的点追逐游戏作为家庭作业,我无法弄清楚如何将难度选择从索引页面延伸到实际游戏页面。

索引页

<form id="difficulty" name="difficulty" action="game.html">
  <input type="radio" name="diff" id="easyDiff" value="easy">
  <label for="easyDiff">Easy</label>
  <input type="radio" name="diff" id="medDiff" value="medium" checked="checked">
  <label for="medDiff">Medium</label>
  <input type="radio" name="diff" id="hardDiff" value="hard">
  <label for="hardDiff">Hard</label>
  <input type="submit" value="Start Game!" onClick="setDifficulty()"/>
</form>

游戏页面

<html>
  <head>
    <title>DotSmasher</title>
    <link rel="stylesheet" href="dotSmasher.css" type="text/css">
    <script src="dotSmasher.js" type="text/javascript"></script>
  </head>

  <body onLoad="setGameAreaBounds(); startGameTimer()" onResize="setGameAreaBounds()">
    <div id="scoreLabel">Score: 0</div>
    <div id="pageTitle">DotSmasher</div>
    <div id="start">
      <button id="startButton" onClick="start()">Start</button>
    </div>
    <div id="stop">
      <button id="stopButton" onClick="pause()">Stop</button>
    </div>
    <div id="gameArea">
      <button id="dot" onClick="detectHit()"></button>
    </div>
  </body>
</html>

JavaScript代码

在页面开头实例化变量计数,计时器和难度

var score = 0;
var aWidth;
var aHeight;
var timer;

var count = 30;
var counter = setInterval(startGameTimer, 1000);
var difficulty;

function startGameTimer(){
    count -= 1;
    if (count <= 0){
        clearInterval(counter);
        clearTimeout(timer);
        alert("Game has ended, Thank you for playing on " + difficulty + "!");
        return;
    }

}

function setDifficulty(){
    var radioButtons = document.getElementsByName("diff");
    for (var i = 0; i < radioButtons.length; i++) {
        if (radioButtons[i].checked) {
            difficulty = radioButtons[i].value;

        }
    }
}

出于某种原因,我收到了一个未定义的错误,无法弄清楚它可能是什么。

1 个答案:

答案 0 :(得分:1)

您需要将自己的脚本放在页面顶部的head标记中,试试这个:

<script>
    function setDifficulty(){
        var radioButtons = document.getElementsByName("diff");
        for (var i = 0; i < radioButtons.length; i++) {
            if (radioButtons[i].checked) {
                difficulty = radioButtons[i].value;
                alert(difficulty);
            }
        }
    }
</script>
<input type="radio" name="diff" id="easyDiff" value="easy">
        <label for="easyDiff">Easy</label>
        <input type="radio" name="diff" id="medDiff" value="medium" checked="checked">
        <label for="medDiff">Medium</label>
        <input type="radio" name="diff" id="hardDiff" value="hard">
        <label for="hardDiff">Hard</label>
        <input type="submit" value="Start Game!" onclick="setDifficulty();"/>

这是DEMO