[英]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.