javascript 尝试从 JSON 文件填充 JQuery 中的列表。如何调试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19581204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:02:25  来源:igfitidea点击:

Trying to populate a list in JQuery from a JSON file. How to debug?

javascriptjqueryhtmljsonfirebug

提问by Amru E.

So I have a JSON file I need to get Quiz questions from. For now, I am simply storing the questions in an array as an object. Each question object has 'text' (the question itself), 'choices' (an array of possible answers), and 'answer' (an int corresponding to the location of the correct answer choice).

所以我有一个 JSON 文件,我需要从中获取测验问题。现在,我只是将问题作为对象存储在数组中。每个问题对象都有“文本”(问题本身)、“选择”(一组可能的答案)和“答案”(对应于正确答案选择位置的整数)。

How can I check that I'm storing the question objects correctly? I want to create a list of questions and I tried populating my list with questions[i].text and it didn't work. I installed Firebug to debug what was going on, but I am not entirely sure how to make the best use of it.

如何检查我是否正确存储了问题对象?我想创建一个问题列表,我尝试用 questions[i].text 填充我的列表,但没有用。我安装了 Firebug 来调试正在发生的事情,但我不完全确定如何充分利用它。

The JSON is in this format:

JSON 格式如下:

{
"text": "What does the author least like about Eclipse?", 
"choices": [
    "The plugin architecture.",
    "FindBugs.",
    "Refactoring.",
    "The Run As menu."],
"answer": 3
}

My JavaScript file:

我的 JavaScript 文件:

$(document).ready(function(){

var questions=[];
$.getJSON('quiz.js',function(data){

     var i=0;
     for(i=0;i<data.length;i++){
        questions[i]=[String(data[i].text),String(data[i].choices),int(data[i].answer)];

    }

    var list = $('#list')
    $(questions).each(function(_, text) {
    var item = $('<li/>')
    var link = $('<a/>').html(text)
    link.click(function() { alert(text) })
    item.append(link)
    list.append(item)
    })

    $('#list').listview('refresh')


});
})

Finally, some HTML:

最后,一些 HTML:

 <div data-role="content">
    <ul id="list" data-role="listview">
    </ul>
</div>

I know it's a long question but I really appreciate any help. The end goal is to have a list of questions that, when clicked, displays the answer choices and provides a toast to notify the user if the selected option is correct or not. I also want to highlight the question in the list in Green if answered correctly, and Red otherwise.

我知道这是一个很长的问题,但我真的很感激任何帮助。最终目标是有一个问题列表,当点击这些问题时,会显示答案选项并提供提示以通知用户所选选项是否正确。如果回答正确,我还想用绿色突出显示列表中的问题,否则用红色突出显示。

EDIT:

编辑:

Working code:

工作代码:

$(document).ready(function(){

$.getJSON('quiz.js',function(data){

var questions = data;
var list = $('#list')

$(questions).each(function(index, object) {

 $.each(object, function(key, value){

    if(key === 'text'){
        //do something with qustion

            var item = $('<li/>')
            var link = $('<a/>').html(value)
            link.click(function() { alert(value) })
            item.append(link)
            list.append(item)
            $('#list').listview('refresh')
        }

      });
    });

  });
});

采纳答案by Corey Rowell

you're using eachwrong for one. Number two you have to realize that you're getting an Object of Objects back in your JSON response. You need to iterate over each object that contains your question/answer data and further iterate over that question/answer object. Further you have an array nested in that nested Object and need to loop through that to get your questions. Take a look at some pseudo code:

你用each错了。第二,您必须意识到您正在 JSON 响应中返回一个 Object of Objects。您需要迭代包含您的问题/答案数据的每个对象,并进一步迭代该问题/答案对象。此外,您有一个嵌套在该嵌套对象中的数组,需要遍历该数组以获取您的问题。看一段伪代码:

//will give you each object your data
$.each(data, function(key, object){

    //do something with my [Object, Object]
    $.each(object, function(key, value){

        if(key === 'text'){
            //do something with qustion
        }

        if(key === 'choices'){
            //loop over array
        }
    }
}

回答by Sridhar R

try this..

试试这个..

var ques=[];
$.getJSON('quiz.js',function(data){
for(var i in data)
{
var text =data[i].text;
var choic=data[i].choices;
var output='<li>'+text+'</li>';
}
$('#list').empty().append(output);
});

回答by Corey Rowell

Are you actually iterating over the array of choices when you get to it? here's a fiddle

当你得到它时,你实际上是在迭代选择数组吗?这是一把小提琴

You either need to use a $.eachfound in jQuery or if you want pure javascript

您要么需要使用$.each在 jQuery 中找到的,或者如果您想要纯 javascript

for (property in object) {
  if (object.hasOwnProperty(property)) {
    // do stuff
  }
} 

回答by me_digvijay

As far as I can understand: The questionsis an array of few elements. These elements are in turn arrays of three elements (text, choices and answer).

据我所知:这questions是一个包含几个元素的数组。这些元素依次是三个元素(文本、选择和答案)的数组。

You are using the question array in the jquery selector for the eachstatement.

您在each语句的 jquery 选择器中使用问题数组。

Following is a better way to do what you want:

以下是做你想做的更好的方法:

$.each(questions, function (i, value) {
    var text = questions[i][0];
    var choice = questions[i][1];
    var answer = questions[i][2];
    var output='<li>'+text+'</li>';
    // rest of your code using text, choices and answers
});