jquery将输入值存入空数组元素

时间:2013-04-04 19:09:28

标签: jquery html arrays forms input

我有这个数组

 var foods = new Array();
    foods = [
        { id:  1, correct:'icecream', display: 'icecream',  response: ''},
        { id:  2, correct:'sundae', display: 'sundae',  response: ''},

    ];

和这个html div

<div id="showfoods" class="foodlist">
    <div <input id="inputFoodChoice"class="foodinput" /></div>
        </div>

这是项目表单部分会发生什么的jquery部分

function FoodDisplay()
    {
    var txtTrial = "";

    $("#showfoods").hide();

    txtTrial = trials[curTrial].display;

    $("#textPrompt").html(txtTrial);

    $("#showfoods").show();

    $("#inputFoodChoice").val('');
    $("#inputFoodChoice").focus();


}

单词“icecream”将出现在其下方的表格框中,用户将输入的确切单词icecream,然后按enter键(ltr == 13)

我想要的是将人物输入的值存储到食物数组的空“响应”部分,然后将其与食物数组中的“正确”值进行比较。取决于该人是否正确,会弹出一条消息说你得到了它!或者不正确!

在该消息出现之后不久,它将以相同的方式显示单词“sundae”。

我无法存储输入值/将其与正确的值进行比较。 有人可以帮忙吗?

我想在某种意义上我希望它“编辑”食物数组中的响应值,所以我可以将该值与输入值进行比较,或者甚至是必要的?

1 个答案:

答案 0 :(得分:1)

它有助于存储用户的响应,以防您想要输出他们的工作方式以及他们为每个人输入的内容的摘要。

您需要一个函数来检查列表中的输入值:

var checkInputValue = function () {
    trials[curTrial].response = input.val();    // store user's input into response
    if (trials[curTrial].response === trials[curTrial].correct) {    // users input is equal to the correct text
        alert('Correct!');
    } else {
        alert('Incorrect!');
    }
    curTrial++;    // next trial
    showTrial();
};

我建议您隔离显示问题的逻辑,这样您就可以为每个qustion调用相同的函数,我将代码移到这里:

var curTrial = 0;
var input = $("#inputFoodChoice");
var container = $("#showfoods");
var prompt = $("#textPrompt");
var showTrial = function() {
    container.hide();
    if (curTrial < trials.length) {
        txtTrial = trials[curTrial].display;
    } else {
        alert("No more questions left.");
    }
    prompt.html(txtTrial);
    container.show();
    input.val('');
    input.focus();        
}; 

请参阅小提琴:http://jsfiddle.net/amyamy86/jSyfy/

我的示例使用按钮click来触发checkInputValue(),您可以根据需要对其进行更改,并为输入附加keydown / keypressed事件键。