[英]How to append an array to a div?
所以我在讓我的數組加載到我的 HTML 中的指定區域時遇到了一些麻煩,目前 HTML 看起來像這樣:
<body>
<div id="japan"></div>
</body>
<script src="Fisher-Yates.js"></script>
我的 Javascript 是:
let hiragana = [あ, い, う, え, お];
let result = shuffle(hiragana);
let div = document.getElementById('japan');
for (let i = 0; i < result.length; i++) {
div.appendChild(result[i]);
}
如果我將 div.appendChild 替換為 document.body.appendChild ,它將出現在正文中,所以我認為某些代碼應該可以工作,我只是不確定我錯過了什么!
編輯:我還應該提到,數組是我想隨機加載的圖像的變量,這是代碼的 rest:
function shuffle(array) {
var m = array.length,
t,
i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
let あ = document.createElement("img");
あ.src = "/images/あ.png";
//あ.setAttribute("width", "25%");
let い = document.createElement("img");
い.src = "/images/い.png";
let う = document.createElement("img");
う.src = "/images/う.png";
let え = document.createElement("img");
え.src = "/images/え.png";
let お = document.createElement("img");
お.src = "/images/お.png";
嘗試在代碼頂部添加圖像元素。
let あ = document.createElement("img"); あ.src = "/images/あ.png"; //あ.setAttribute("width", "25%"); let い = document.createElement("img"); い.src = "/images/い.png"; let う = document.createElement("img"); う.src = "/images/う.png"; let え = document.createElement("img"); え.src = "/images/え.png"; let お = document.createElement("img"); お.src = "/images/お.png"; let hiragana = [あ, い, う, え, お]; let result = shuffle(hiragana); let div = document.getElementById('japan'); for (let i = 0; i < result.length; i++) { div.appendChild(result[i]); } function shuffle(array) { var m = array.length, t, i; while (m) { i = Math.floor(Math.random() * m--); t = array[m]; array[m] = array[i]; array[i] = t; } return array; }
<body> <div id="japan"></div> </body> <script src="Fisher-Yates.js"></script>
而不是div.appendChild(result[i]);
您是否嘗試過以下代碼:
<body>
<div id="japan"></div>
</body>
<script src="Fisher-Yates.js"></script>
let hiragana = [あ, い, う, え, お];
let result = shuffle(hiragana);
div = document.getElementById('japan');
for (let i = 0; i < result.length; i++) {
div.innerHTML = div.innerHTML + result[i];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.