简体   繁体   English

遍历对象数组并将每个元素插入html

[英]Loop through object array and insert each element into html

I have an object that includes both questions and answers. 我有一个既包含问题又包含答案的对象。 I'm trying to loop through the first set of answers in the object and append them to the HTML. 我正在尝试遍历对象中的第一组答案,并将它们附加到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]);
    };
});

You need to create an li like 您需要创建一个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"))
    };
});

In your code li is considered as text to be appended, which is then overridden by calling .html() 在您的代码中, li被视为要附加的文本,然后通过调用.html()覆盖它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何遍历对象数组并访问每个数组内的属性以显示在 html 元素中? - how to loop through an array of objects and access the properties inside each array to display in an html element? 循环遍历对象数组,并按对象元素ID返回每个总计值的和 - Loop through array of objects and return sum of each total values by object element id 如何遍历数组对象并检查每个元素以查看是否已定义? - How can I loop through an array object and check each element to see if one is defined? 如何循环遍历 object 并获取每个元素的索引并将其存储在数组中? - How can I loop through an object and get the index of each element and store it in an array? 遍历每个元素并将值添加到新对象。 将这些对象添加到数组并访问其值 - Loop through each element and add values to a new object. Add these objects to array & access their values 如何遍历每个元素上调用 jquery.each 的数组? - How to loop through an array calling jquery.each on each element? 遍历数组并使用每个数组值更改一个html元素 - Looping through an array and changing an html element with each array value 在each()中遍历数组 - loop through array in each() 遍历数组,将每个项目添加到对象中,然后将其推入Javascript中的数组 - Loop through an Array, add each item to an object and push it to an array in Javascript 循环遍历数组,将每个值分配给Javascript / Jquery中的元素属性 - Loop through array, assign each value to an element attribute in Javascript / Jquery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM