[英]How can I put elements of an array inside object which is inside an array in separate divs?
我想動態地將數組的元素放在單獨的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();
您可以使用循環為每個數組元素創建一個<div>
元素,而不是調用join()
將所有數組元素拼接在一個字符串中。 我建議你看一下數組的map()
函數。
我希望下一個代碼可以幫助你,基本上我假設你有一個帶有問題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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.