当使用Javascript检查复选框时,如何从JSON文件中获取数据?

时间:2022-08-22 10:24:03

I'm a beginner in javascript and I'm trying to build a little flashcard game that allows users to select different libraries of flashcards when they click a checkbox and I am having some difficulty implementing this feature. What I want my code to do is change the dataset that gets displayed when someone clicks on a checkbox of their choice.

我是一个javascript初学者,我正在尝试构建一个flash卡片游戏,当用户点击一个复选框时,可以选择不同的flash卡片库,我在实现这个特性时遇到了一些困难。我希望我的代码做的是更改当有人单击他们选择的复选框时显示的数据集。

Here is a picture of the checkboxes and the flashcards:

这是复选框和抽认卡的图片:

当使用Javascript检查复选框时,如何从JSON文件中获取数据?

This is the HTML code for the checkboxes:

这是复选框的HTML代码:

<div id="flashcard_sets">
    <div id="card_group">
        <h3><u>Choose Flashcard Set</u></h3>
        <input type="checkbox" id="question_words" name="Question Words" value="Question Words" class="vocab">Question Words
        <input type="checkbox" id="verbs" name="Verbs" value="Verbs" class="vocab">Verbs
        <input type="checkbox" id="nouns" name="Nouns" value="Nouns" class="vocab">Nouns
    </div>
</div>

My data is saved in an external json file stored in this variable: var jsonUrl = "questionsAndAnswersItalian.json"; that contains this information:

我的数据保存在这个变量中存储的一个外部json文件中:var jsonUrl = "questionsAndAnswersItalian.json";包含这些信息:

{"Question Words":[{"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é"}],
"Verbs":[{"q":"What is the verb for 'I am'?","a":"Sono"},
{"q":"What is the verb for 'you are'?","a":"tu sei"},
{"q":"What is the verb for 'he is'?","a":"lui è"}],
"Nouns":[{"q":"gioco","a":"game"},
{"q":"buco","a":"hole"},
{"q":"amico","a":"friend"}]}

This is the javascript function that displays the flashcard:

这是显示抽认卡的javascript函数:

var jsonUrl = "questionsAndAnswersItalian.json";
var cardIndex = 0;
var qs;
var numCards;
var maxIndex;
var isFlipped = 0;

function displayCard() {
    $("#card").fadeOut(400,function(){
        colorIndex = getRandomInteger(0,3);
        $("#card").addClass(colorClasses[colorIndex])
        isFlipped = 0;
        var newHtml = "<h2>Question Words</h2>";
        var chosen_one = $("#card_group input[type=checkbox]:checked")
        if(chosen_one){
            var selection = chosen_one.attr("name");
            newHtml += qs["selection"][cardIndex]["q"];
        }else{
            newHtml += qs["Question Words"][cardIndex]["q"];
        }
        document.getElementById("question").innerHTML = newHtml;
    }).fadeIn(400);
}

This is the code that grabs the external json data to display on the flashcard:

这是获取外部json数据并在抽认卡上显示的代码:

var jsonUrl = "questionsAndAnswersItalian.json";
var cardIndex = 0;
var qs;
var numCards;
var maxIndex;
var isFlipped = 0;

function init() {
    $.getJSON(jsonUrl, function(jsonObject) {
        qs = jsonObject;
        var chosen_one = $("#card_group input[type=checkbox]:checked")
        if(chosen_one){
            var selection = chosen_one.attr("name");
            numCards = qs["selection"].length;
        }else{
            numCards = qs["Question Words"].length;
        }
        maxIndex = numCards-1;
        displayCard();
    });
}

I know I definitely did something wrong and I've tried several solutions but now I don't really know what to do to get this working. If anyone could provide some help or advice on this, I'd greatly appreciate it.

我知道我肯定做错了什么,我尝试了几种解决方案,但现在我真的不知道该怎么做才能让它奏效。如果有人能提供一些帮助或建议,我将非常感谢。

Thanks!

谢谢!

Link to full code that isn't working: http://plnkr.co/edit/Uhau56byCGOLJiQxmFFg?p=preview

链接到无效的完整代码:http://plnkr.co/edit/uhau56bycgoljiqxmffg?

Link to original code without the code you wrote, and with javascript functions embedded into the HTML file. You can take a look at this to see what I want to do with my code: http://plnkr.co/edit/kxzTPX3VhYKZGNDkDoWX?p=preview

链接到原始代码,无需编写代码,并将javascript函数嵌入到HTML文件中。您可以看一下这里,看看我想对代码做什么:http://plnkr.co/edit/kxztpx3vhykzgndkdowx?

3 个解决方案

#1


1  

Firstly, you want to use radio buttons because you only want one to be selected.

首先,您需要使用单选按钮,因为您只需要选择一个。

So I've slightly re-written it to get you on the right path.

我稍微重写了一遍,让你们找到正确的路径。

function init() {
    $.getJSON(jsonUrl, function(jsonObject) {
        qs = jsonObject;
        changeCard("Question Words");
    });
}

$('.vocab').change(function () {
  var chosen_one = $(this).val();
  changeCard(chosen_one);
});

var changeCard = function(chosen_one) {
  $("#card").fadeOut(400,function(){
      isFlipped = 0;
      var newHtml = qs[chosen_one][cardIndex]["q"];
      maxIndex = qs[chosen_one].length;
      $('#questionTitle').html(chosen_one);
      $('#question').html(newHtml);
      console.log(maxIndex);
  }).fadeIn(400);
};

HTML:

HTML:

<div id="card">
  <h2 id="questionTitle"></h2>
  <div id="question"></div>
</div>

<div id="flashcard_sets">
<div id="card_group">
    <h3><u>Choose Flashcard Set</u></h3>
    <label for="question_words"><input type="radio" id="question_words" name="vocab" value="Question Words" class="vocab" checked>Question Words</label>
    <label for="verbs"><input type="radio" id="verbs" name="vocab" value="Verbs" class="vocab">Verbs</label>
    <label for="nouns"><input type="radio" id="nouns" name="vocab" value="Nouns" class="vocab">Nouns</label>
</div>

plunker: http://plnkr.co/edit/WjDKys?p=preview

砰砰作响:http://plnkr.co/edit/WjDKys?p=preview

#2


0  

The key part that is going wrong here is that

这里出错的关键是

document.getElementsByTagName("input")

is returning a NodeList. In order to look at any parameters of this list, it needs to be iterated. A more appropriate approach would be to look for the checked one.

是返回一个节点列表。为了查看这个列表的任何参数,需要迭代它。一种更合适的方法是查找检查过的那个。

var chosen_one = $("#card_group input[type=checkbox]:checked");

however, the problem here is that there can be up to 3 checked. Addressing this will fix the problem in your code.

但是,这里的问题是最多可以检查3次。解决这个问题将修复代码中的问题。

#3


0  

    if(document.getElementsByTagName("input").checked){

This line is definitely going to be a problem. document.getElementsByTagName returns an array of Elements, and because arrays do not have a checked attribute, this statement will evaluate to undefined. Because undefined has a false truth value, anything inside of your if statement will not be executed.

这条线肯定会是个问题。文档。getElementsByTagName返回一个元素数组,由于数组没有检查属性,这个语句将计算为undefined。因为undefined具有一个假真值,所以if语句中的任何内容都不会被执行。

Now, this does not mean that you can't search through the array of input elements yourself to find the checked box. You will have to do a for-loop to check the boxes yourself:

这并不意味着你不能自己搜索输入元素的数组来找到复选框。你将不得不做一个for循环来检查你自己的箱子:

var chosen_one;
for (var i=0; i < document.getElementsByTagName("input").length; i++){
    var box = document.getElementsByTagName("input")[i];
    if (box.checked) {
        chosen_one = changeCardset();
        numCards = qs["chosen_one"].length;
    }
}
if (!chosen_one) numCards = qs["Question Words"].length;

You will also have to change your changeCardset function to have a similar for-loop for finding the box (if any) that is checked.

您还必须更改changeCardset函数,使其具有类似的for循环来查找选中的框(如果有的话)。

#1


1  

Firstly, you want to use radio buttons because you only want one to be selected.

首先,您需要使用单选按钮,因为您只需要选择一个。

So I've slightly re-written it to get you on the right path.

我稍微重写了一遍,让你们找到正确的路径。

function init() {
    $.getJSON(jsonUrl, function(jsonObject) {
        qs = jsonObject;
        changeCard("Question Words");
    });
}

$('.vocab').change(function () {
  var chosen_one = $(this).val();
  changeCard(chosen_one);
});

var changeCard = function(chosen_one) {
  $("#card").fadeOut(400,function(){
      isFlipped = 0;
      var newHtml = qs[chosen_one][cardIndex]["q"];
      maxIndex = qs[chosen_one].length;
      $('#questionTitle').html(chosen_one);
      $('#question').html(newHtml);
      console.log(maxIndex);
  }).fadeIn(400);
};

HTML:

HTML:

<div id="card">
  <h2 id="questionTitle"></h2>
  <div id="question"></div>
</div>

<div id="flashcard_sets">
<div id="card_group">
    <h3><u>Choose Flashcard Set</u></h3>
    <label for="question_words"><input type="radio" id="question_words" name="vocab" value="Question Words" class="vocab" checked>Question Words</label>
    <label for="verbs"><input type="radio" id="verbs" name="vocab" value="Verbs" class="vocab">Verbs</label>
    <label for="nouns"><input type="radio" id="nouns" name="vocab" value="Nouns" class="vocab">Nouns</label>
</div>

plunker: http://plnkr.co/edit/WjDKys?p=preview

砰砰作响:http://plnkr.co/edit/WjDKys?p=preview

#2


0  

The key part that is going wrong here is that

这里出错的关键是

document.getElementsByTagName("input")

is returning a NodeList. In order to look at any parameters of this list, it needs to be iterated. A more appropriate approach would be to look for the checked one.

是返回一个节点列表。为了查看这个列表的任何参数,需要迭代它。一种更合适的方法是查找检查过的那个。

var chosen_one = $("#card_group input[type=checkbox]:checked");

however, the problem here is that there can be up to 3 checked. Addressing this will fix the problem in your code.

但是,这里的问题是最多可以检查3次。解决这个问题将修复代码中的问题。

#3


0  

    if(document.getElementsByTagName("input").checked){

This line is definitely going to be a problem. document.getElementsByTagName returns an array of Elements, and because arrays do not have a checked attribute, this statement will evaluate to undefined. Because undefined has a false truth value, anything inside of your if statement will not be executed.

这条线肯定会是个问题。文档。getElementsByTagName返回一个元素数组,由于数组没有检查属性,这个语句将计算为undefined。因为undefined具有一个假真值,所以if语句中的任何内容都不会被执行。

Now, this does not mean that you can't search through the array of input elements yourself to find the checked box. You will have to do a for-loop to check the boxes yourself:

这并不意味着你不能自己搜索输入元素的数组来找到复选框。你将不得不做一个for循环来检查你自己的箱子:

var chosen_one;
for (var i=0; i < document.getElementsByTagName("input").length; i++){
    var box = document.getElementsByTagName("input")[i];
    if (box.checked) {
        chosen_one = changeCardset();
        numCards = qs["chosen_one"].length;
    }
}
if (!chosen_one) numCards = qs["Question Words"].length;

You will also have to change your changeCardset function to have a similar for-loop for finding the box (if any) that is checked.

您还必须更改changeCardset函数,使其具有类似的for循环来查找选中的框(如果有的话)。