函数未接收来自<表单>标签

Function not receiving receiving userinput from <form> tag

本文关键字:lt gt 标签 表单 函数      更新时间:2023-09-26

我正在尝试制作一个涉及音乐间歇游戏的简单程序。它会让用户尝试用一组给定的笔记来回答正确的间隔。但是,我的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>

在浏览器中检查控制台:

"oneToTwo未定义"

也许您可以将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;
}