![](/img/trans.png)
[英]How do I Filter a JSON file to retrieve data for HTML with Javascript
[英]How do I input text via an HTML form and retrieve data from a JSON file as a response using Javascript?
我正在嘗試制作一個小卡片問答游戲,我正在嘗試實現一個功能,有人可以將文本輸入到輸入區域,然后在他們按下輸入后,屏幕上會顯示“正確”或“不正確”字樣1在輸入區域為空並且下一個問題被加載之前的第二個。
這是我正在做的事情的視覺效果:
特別是,這是生成下面輸入文本區域的HTML代碼:
<form id="answers">
<input type="text" name="inputtext" id="answer" style="width: 100%; height: 30px;" placeholder="Enter your answer..." onkeyup="checkAnswer(this,event);" autofocus><br>
</form>
這是JSON文件,保存為:questionsAndAnswersItalian.json
[{"q":"What is the word for 'where' in Italian?","a":"Dove"},
{"q":"What is the word for 'when' in Italian?","a":"Quando"},
{"q":"What is the word for 'why' in Italian?","a":"Perché"}]
這是我寫的javascript代碼無法正常工作:
var jsonUrl = "questionsAndAnswersItalian.json";
var qs;
var numCards;
var maxIndex;
function checkAnswer(input, event){
if(event.keyCode == 13){
var answer = document.getElementById("answer").value.toLowerCase();
var questionNumber = 0;
for(var i = 0; i<jsonUrl.length; i++){
if(answer == jsonUrl[questionNumber]["a"].toLowerCase()){
setTimeout(correct_input, 1000);
input.value = "";
}else{
setTimeout(incorrect_input, 1000);
input.value = "";
}
questionNumber++;
}
}
}
function correct_input(){
input.value = "Correct!";
}
function incorrect_input(){
input.value = "Incorrect!";
}
function init() {
$.getJSON(jsonUrl, function(jsonObject) {
qs = jsonObject;
numCards = qs.length;
maxIndex = numCards-1;
displayCard();
});
}
這些功能不像我預期的那樣有效,我想知道是否有人可以告訴我哪里出錯了。
如果您需要更多信息來了解我在這里做的事情,請不要猶豫!
任何幫助或建議將不勝感激!
謝謝。
在這部分:
for(var i = 0; i<jsonUrl.length; i++){
if(answer == jsonUrl[questionNumber]["a"].toLowerCase()){
setTimeout(correct_input, 1000);
input.value = "";
}else{
setTimeout(incorrect_input, 1000);
input.value = "";
}
questionNumber++;
}
你循環遍歷String(jsonUrl),而不是你的jsonObject。 請改用qs
。
編輯:
這是一個有效的jquery代碼:
$('#answer').keyup(function(event) {
var code = event.keyCode || event.which;
if (code == 13) {
var answer = $(this).val().toLowerCase();
var goodAnswer = qs[currentCard].a.toLowerCase();
if (answer == goodAnswer) {
setTimeout(correct_input, 1000);
}
else {
setTimeout(incorrect_input, 1000);
}
$(this).val('');
}
});
聲明var currentCard = null;
作為全局並在displayCard()
中設置其值,我認為你做了隨機或類似的事情。
使用此代碼,您必須刪除onkeyup="checkAnswer(this,event);"
。
jsfiddle: http : //jsfiddle.net/u7bkH/
setTimeout
函數需要異步回調。
編輯一個更完整的示例,但請注意 ,它只顯示了根據您的要求正確使用setTimeout
的方法。 您需要完成對答案正確性的適當檢查。
所以,將代碼更改為此
$('#answer').keyup(function(event) {
var code = event.keyCode || event.which;
if (code == 13) {
var input = $(this);
var answer = input.val().toLowerCase();
if (answer == "correct") {
input.val("Correct!");
}
else {
input.val("Incorrect!");
}
setTimeout(
function(){
input.val("");
},1000);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.