从.each循环中获取最终对象。

时间:2014-08-29 18:23:24

标签: jquery object each

我正在使用jquery进行简单的测验。我正在尝试将问题,答案(内容)和答案(索引)放入对象中。这是我到目前为止的代码和小提琴。

    $('.submit').on('click', function() {

        $('li[data-question]').each(function(i){

            question = $(this).attr('data-question');
            answer = $(this).find('input:checked').parent().text().trim();
            index = $(this).find('input:checked').parent().parent().parent().index() + 1;

            $('body').data(question, {
                "question":question,
                "index":index,
                "answer":answer
            });

            console.log( $('body').data() );

        });

    });

http://jsfiddle.net/oe6z9svq/2/

这很有效,但我想从中得到最终的回应对象。目前,它逐步执行每个问题并为每个问题创建一个对象,一次添加一个。

如何以json的形式返回(?)最终结果然后在别处使用?

1 个答案:

答案 0 :(得分:1)

扩展MelancialUK的评论,将所有问题都放在一个数组中:

$('.submit').on('click', function () {

    var questions = [];

    $('li[data-question]').each(function (i) {

        question = $(this).attr('data-question');
        answer = $(this).find('input:checked').parent().text().trim();
        index = $(this).find('input:checked').parent().parent().parent().index() + 1;

        questions.push({
            question: question,
            index: index,
            answer: answer
        });

    });

    $('body').data("questions", questions);
    console.log(questions);

});

http://jsfiddle.net/oe6z9svq/3/