函数未从<form>标记接收用户输入

时间:2015-11-28 17:08:32

标签: javascript html forms

我正在尝试制作一个涉及音乐间隔游戏的简单程序。它将让用户尝试使用给定的一组音符来回答正确的音程。但是,我的check()函数出现问题,它将读取用户的答案并使用正确的答案进行检查。问题是,当我运行程序并尝试单击check按钮时,我不会得到任何响应。

这是JavaScript代码:

var notes = ['A','B','C','D','E','F','G'];
var accidentals = ['b','#'];
var notesFull = [];

for (var i = 0; i < notes.length; i++) {
    notesFull.push(notes[i] + accidentals[0]);
    notesFull.push(notes[i]);
    notesFull.push(notes[i] + accidentals[1]);
}
notesFull.splice(5,2);
notesFull.splice(12,2);

var intervals = ["U", "m2", "M2", "m3", "M3", "P4", "T", "P5", "m6", "M6", "m7", "M7"];
function game() {
    var setIntOne = Math.floor(Math.random()*notesFull.length);
    var setIntTwo = Math.floor(Math.random()*notesFull.length);
    var oneToTwo = setIntOne - setIntTwo;
    if (oneToTwo < 0) {
        oneToTwo = oneToTwo * -1
    }
    var ques = "What is the interval going UP from " + notesFull[setIntTwo] + " to " + notesFull[setIntOne] + "?";
    document.getElementById("ques").innerHTML = ques;
}

function check() {
    var usrInp = document.getElementById("usrInp");
    if (usrInp.elements[0].value === intervals[oneToTwo]) {
        var resp = "Correct!";
    }
    else if (usrInp.elements[0].value === "null") {
        var resp = "Please input an interval";
    }
    else {
        var resp = "Sorry! Try again";
    }
    document.getElementById("resp").innerHTML = resp;
}

这是HTML代码:

<button onclick="game()">Click here for test</button>
<p id="ques"></p>
<form id="usrInp">
    Type Answer Here: <input type="text" name="usrAns">
</form>
<button onclick="check()">Check</button>
<p id="resp"></p>

1 个答案:

答案 0 :(得分:0)

在浏览器中检查控制台:

  

&#34; oneToTwo未定义&#34;

也许您可以将var oneToTwo移到功能之外。

例如:

var notes = ['A','B','C','D','E','F','G'];
var accidentals = ['b','#'];
var notesFull = [];
var oneToTwo;
for (var i = 0; i < notes.length; i++) {
    notesFull.push(notes[i] + accidentals[0]);
    notesFull.push(notes[i]);
    notesFull.push(notes[i] + accidentals[1]);
}
notesFull.splice(5,2);
notesFull.splice(12,2);

var intervals = ["U", "m2", "M2", "m3", "M3", "P4", "T", "P5", "m6", "M6", "m7", "M7"];
function game() {
    var setIntOne = Math.floor(Math.random()*notesFull.length);
    var setIntTwo = Math.floor(Math.random()*notesFull.length);
    oneToTwo = setIntOne - setIntTwo;
    if (oneToTwo < 0) {
        oneToTwo = oneToTwo * -1
    }
    var ques = "What is the interval going UP from " + notesFull[setIntTwo] + " to " + notesFull[setIntOne] + "?";
    document.getElementById("ques").innerHTML = ques;
}

function check() {
    var usrInp = document.getElementById("usrInp");
    if (usrInp.elements[0].value === intervals[oneToTwo]) {
        var resp = "Correct!";
    }
    else if (usrInp.elements[0].value === "null") {
        var resp = "Please input an interval";
    }
    else {
        var resp = "Sorry! Try again";
    }
    document.getElementById("resp").innerHTML = resp;
}