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

我有这个arrays

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

和这个html 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)

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

在该消息出现多长时间后,它将以相同的方式显示“圣代”一词。

我在存储输入值/将其与正确值进行比较时遇到问题。 有人可以帮忙吗?

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

它有助于存储用户的响应,以防您想要输出它们的执行方式和每个类型的输入摘要。

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

 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() ,您可以根据需要更改它,并为enter键附加keydown / keypressed事件。