簡體   English   中英

在使用for循環輸出數組時,如何將所有內容輸出到一個新的div中? javascript

[英]While outputting an array with a for loop, how can i output all of the contents into a single, new div? javascript

我使用innerHTML + =通過for循環輸出一個數組的值,以便添加到當前div的內容中,我們將其稱為div1(在代碼中稱為currentQuestions)。

輸出數組值的功能將被多次使用,因為存儲在數組中的值會隨着用戶輸入的變化而變化。 這意味着div1的輸出列表將會越來越多。

但是問題是,對於數組迭代的每組數據,我都需要將它們一起存儲在自己的div中(在div1內),與通過同一函數的不同調用生成的其他組分開存儲。

它們不需要具有唯一的ID,但是需要它們來調用onclick函數,該函數只會影響被單擊的div。

這是我到目前為止所擁有的:

arrayLength = answers.length
for (var j = 0; j < arrayLength; j++)
    {
    document.getElementById('currentQuestions').innerHTML += answers[j] + '<br />'
    }

如您所見,到目前為止,我所擁有的只是for循環。 我不能將一個div添加到innerHTML中,因為這樣它將為每次迭代創建一個div,而不是為數組的整個迭代創建一個div。

我沒主意了。 有什么想法嗎?

創建div並將事件處理程序附加到循環之前,如下所示:

var subdiv = document.createElement('div'), // Creates a new element to the DOM
    arrayLength = answers.length;

subdiv.addEventListener('click', function () {...}); // Attach a click listener

for (var j = 0; j < arrayLength; j++) {
    subdiv.innerHTML += answers[j] + '<br />'; // Add some content to newly-created DIV
}
document.getElementById('currentQuestions').appendChild(subdiv); // Append the newly-created element to the document.

讓您的生活更輕松,並嘗試使用jQuery ...

此示例將在他們單擊的div中使用html並將其附加到#currentQuestions div ...

$('body').on('click', '.class_of_div_they_click_on', function(event) {
    var div_content = $(this).html();
    $("#currentQuestions").append(div_content + '<br>');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM