如何将数组的元素放入单独的div中位于数组内部的对象内?

时间:2019-05-17 21:16:07

标签: javascript

我想将数组的元素动态地放在单独的div中。数组在对象内部,而对象在数组内部。我想在单独的div中显示options属性的每个值。如何通过javascript实现呢?感谢您的大力帮助。

 var antonyms = [

 {
   question: "soft",
   options: ["dark", "white", "heavy", "hard", "down", "pretty", 
   "butter", "cotton"],
   answer: "hard"

  } ]


var x = "";

var i = 0;

function elements() {

if (i < antonyms.length) {

x += '<div class=option>' + antonyms[i].options.join(" ") + '</div>';

document.getElementById('container').innerHTML = x;

 i++;

    }

    x = "";

   }

elements();

2 个答案:

答案 0 :(得分:0)

您可以使用循环为每个数组元素创建一个join()元素,而不是调用<div>来将所有数组元素混成一个字符串。我建议您查看数组的map()函数。

答案 1 :(得分:0)

我希望接下来的代码对您有所帮助,基本上,我假设您有一个带有问题objects外部数组,并且对于每个数组,您都需要生成一个HTML结构。因此,我将定义一个方法,该方法采用一个问题对象并生成相关的HTML结构,然后您可以为每个问题或具体问题调用该方法。

var antonyms = [
  {
    question: "soft",
    options: ["dark", "white", "heavy", "hard", "down", "pretty", "butter", "cotton"],
    answer: "hard"
  },
  {
    question: "test",
    options: ["one", "two"],
    answer: "two"
  }
];

// Define a method that generate the HTML for one question.
function getQuestionHtml(q)
{
    let qHtml = "<h2>" + q.question + " options:</h2>";
    qHtml += q.options.map(o => '<div class="option">' + o + '</div>').join("");
    return qHtml;
}

// Start showing the first question. Click event will show next question.

let container = document.getElementById("container");
let button = document.getElementById("btnNext");
let qIdx = 0;
container.innerHTML = getQuestionHtml(antonyms[qIdx]);

button.addEventListener("click", function()
{
    qIdx += 1;

    if (qIdx < antonyms.length)
        container.innerHTML = getQuestionHtml(antonyms[qIdx]);
    else
        button.disabled = true;
});
.option {
    border: 1px solid gray;
    background-color: skyblue;
}
<div id="container">
</div>
<br>
<button id="btnNext" type="button">Next</button>