如何将用户键入输入字段并将其转换为数组?

时间:2014-03-05 18:25:23

标签: javascript

我有一个简单的输入文本框,用户应该在其中复制我呈现的内容。

<h3 id="beginGame">Play</h3>

<h3 id="textOnScreen"></h3>

<form>
<input type="text" id="userInput" style="display: none;"></input>
<button type="button" id="nextButton" style="display: none;">Next</button>
</form>

然后我想把他们输入的内容放到文本框中,并根据当前选择的名为“营养素”的数组索引进行验证。

    var nutrients = [
        "Vitamin B6",
        "Manganese",
        "Vitamin C",
        "Fiber",
        "Potassium",
        "Biotin",
        "Copper"

    ];

最初,我让用户与提示和提醒进行交互。但是,我现在正在尝试将其转换为基于纯HTML元素的界面。

例如我有一个名为ask()的函数 在一开始看起来像这样:

function ask() {
     userInput = prompt("Enter the following into the text field: " + nutrients[i] + ".");
}

但现在看起来像这样:

   function ask() {
        document.getElementById('textOnScreen').innerHTML = "Enter the following into the text field: " + nutrients[i] + ".";
    }

我想解开的当前难题是我的formatText()函数。此功能旨在获取用户输入的内容并对其进行格式化,以匹配存储在数组“营养素”中的值的类型,无论它们如何利用其条目。当我使用提示时,我使用以下代码完成了此操作:

    function formatText() {

    if (userInput === "") {
                    alert("You must enter a value");
                    ask();
                    formatText();
                }

            var answerArray = userInput.split(" ");

            for (var i = 0; i < answerArray.length; i++) {
                answerArray[i] = answerArray[i][0].toUpperCase() + answerArray[i].substring(1).toLowerCase();
            }

            finalAnswer = answerArray.join(" ");
}

然后我将其传递给名为validateAnswer()的函数,该函数看起来像这样

 function validateAnswer() {

        if (finalAnswer === nutrients[i]) {
            alert("You are correct! " + nutrients[i]);
        } else {
            alert("That is incorrect. Please try again.");
            ask();
            formatText();
            validateAnswer();

        }
    }

但是,现在我正在尝试使用innerHTML在屏幕上实际显示文本,并且我使用输入字段来接受用户输入,我不能再使用split()方法了。所以我尝试稍微改变我的代码并将其转换为:

function formatText() {

    if (userInput === "") {
        document.getElementById('textOnScreen').innerHTML = "You must enter a value";
        ask();
        formatText();
    }

    userInput = [];




    for (i; i < userInput.length; i++) {
        userInput[i] = userInput[i][0].toUpperCase() + userInput[i].substring(1).toLowerCase();
    }

    finalAnswer = userInput.join(" ");

}

但是,现在我收到了这个错误:

未捕获RangeError:超出最大调用堆栈大小
formatText
validateAnswer
validateAnswer
validateAnswer
validateAnswer
等...

我意识到我有一个以上的问题,我正在尝试解决这个问题。但是,我现在尝试解决的唯一一个是我的formatText()函数的替代品。如何从输入字段(例如此

)中获取用户输入
<input type="text" id="userInput"></input>

并将其分解为一个数组,以便我可以使用我的formatText()函数?或者我是否必须以不同的方式完全采用它?

下面我将粘贴我正在处理的整个代码片段,这样你就可以看到我以更线性的方式完成了什么,以及它目前所处的位置。非常感谢您的帮助。

function memoNutri() {
    "use strict";

    var nutrients = [
        "Vitamin B6",
        "Manganese",
        "Vitamin C",
        "Fiber",
        "Potassium",
        "Biotin",
        "Copper"

    ],
        finalAnswer, i = 0,
        userInput = document.getElementById('userInput');




    //This function reveals certain elements while hiding others
    function showHide(show, show2, hide) {

        document.getElementById(show).style.display = 'block';

        document.getElementById(show2).style.display = 'block';

        document.getElementById(hide).style.display = 'none';

    }


    showHide("userInput", "nextButton",
        "beginGame");


    //This function is responsible for giving the user instructions
    function ask() {
        document.getElementById('textOnScreen').innerHTML = "Enter the following into the text field: " + nutrients[i] + ".";
    }



    //This function takes the users input and formats it to match the values stored in the array
    function formatText() {

        if (userInput === "") {
            document.getElementById('textOnScreen').innerHTML = "You must enter a value";
            ask();
            formatText();
        }

        userInput = [];




        for (i; i < userInput.length; i++) {
            userInput[i] = userInput[i][0].toUpperCase() + userInput[i].substring(1).toLowerCase();
        }

        finalAnswer = userInput.join(" ");

    }


    //This function checks the users answer against the value stored in the array
    function validateAnswer() {

        if (finalAnswer === nutrients[i]) {
            document.getElementById('textOnScreen').innerHTML = "You are correct! " + nutrients[i];
        } else {
            document.getElementById('textOnScreen').innerHTML = "That is incorrect. Please try again.";
            ask();
            formatText();
            validateAnswer();

        }
    }




    //This code is the execution portion of the function memoNutri
    for (i; i < nutrients.length; i++) {

        ask();

        formatText();

        validateAnswer();

    }
}





var beginGame = document.getElementById('beginGame');
beginGame.onclick = memoNutri;

2 个答案:

答案 0 :(得分:1)

嗯,这是你面临的问题之一。堆栈溢出来自递归函数调用。这两个函数称自己为:

function formatText() {

    if (userInput === "") {
        document.getElementById('textOnScreen').innerHTML = "You must enter a value";
        ask();
        formatText();
    }

function validateAnswer() {

    if (finalAnswer === nutrients[i]) {
        document.getElementById('textOnScreen').innerHTML = "You are correct! " + nutrients[i];
    } else {
        document.getElementById('textOnScreen').innerHTML = "That is incorrect. Please try again.";
        ask();
        formatText();
        validateAnswer();

    }
}

您需要重新构建,以便仅在用户输入新答案时才调用这些函数。否则,当它们第一次被调用时,它们就会循环。

答案 1 :(得分:1)

编辑:我现在测试了这段代码并修复了我的拼写错误。它一直工作到阵列结束,它应该断开。你可以自己想象那个部分。

编辑:http://jsfiddle.net/cXBzA/

你已经过度复杂了。

您需要的所有HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="./scripts/nutrient.js" type="text/javascript"></script>
</head>
<body>
    <p id="confirm"></p>
    <p id="output-nutrient"></p>
    <input type="text" id="input-nutrient">
    <input type="button" id="check-answer" value="Check Answer">
    <div id="js-memory" data=""></div>
</body>
</html>

您需要的所有Javascript(nutrient.js):

var nutrients = ["Vitamin B6", "Manganese", "Vitamin C", "Fiber", "Potassium", "Biotin", "Copper"];

var onLoad = function () {
    document.getElementById("check-answer").onclick = checkAnswer;
    document.getElementById("output-nutrient").innerHTML = nutrients[0];
    document.getElementById("js-memory").setAttribute("data", "0");
};

var checkAnswer = function() {
    var inputNutrient = document.getElementById("input-nutrient").value;
    var outputIndex = document.getElementById("js-memory").getAttribute("data");
    outputIndex = parseInt(outputIndex);
    if(inputNutrient == nutrients[outputIndex]) {
        outputIndex += 1;
        document.getElementById("output-nutrient").innerHTML = nutrients[outputIndex];
        document.getElementById("js-memory").setAttribute("data", outputIndex);
        document.getElementById("confirm").innerHTML = "Correct!";
        document.getElementById("input-nutrient").value = "";
    }
    else {
        document.getElementById("confirm").innerHTML = "Try Again!";
    }
};

if(!window.onload) {
    window.onload = function() {
        onLoad();
    };
}
else {
    var oldWindowLoadFunction = window.onload;
    window.onload = function() {
        oldWindowLoadFunction();
        onLoad();
    };
}