循环遍历对象数组并将每个元素插入到html中

时间:2014-10-14 04:50:05

标签: javascript jquery loops

我有一个包含问题和答案的对象。我正在尝试遍历对象中的第一组答案并将它们附加到HTML。

//create an array with the questions and answers.
var allQuestion = [
    {
        question: "What would your weapon of choice be in battle?",
        answer: [
            "Bow and Arrow",
            "Camouflage",
            "Whiskey.",
            "Snare.",
            "Drones."
        ]
    },
    {
        question: "What is your drink of choice?",
        answer: [
            "Wine.",
            "Beer.",
            "Vodka",
            "Whiskey",
            "Tequila."
        ]
    },
];



$(".one").on("mouseenter", function() {
   //add each answer from first question
    for (i = 0; i < allQuestion[0].answer.length; i++) {
        $(this).find(".list").append("li").html(allQuestion[0].answer[i]);
    };
});

1 个答案:

答案 0 :(得分:0)

您需要创建一个li之类的

$(".one").on("mouseenter", function () {
    //add each answer from first question
    for (i = 0; i < allQuestion[0].answer.length; i++) {
        $('<li />', {
            html: allQuestion[0].answer[i]
        }).appendTo($(this).find(".list"))
    };
});

在您的代码中,li被视为要追加的文字,然后通过调用.html()

来覆盖该文字