首先,我仍然是一个新手,仍在学习,我已经学到了很多东西,并希望在我继续这段旅程时继续学习。 好的,所以我有以下代码并尝试将数组对象附加到具有匹配 ID 的正确 Div。我试过 if 语句不起作用,然后 Switch 语句也没有运气。任何人都可以向我指出正确的方向,评论文本必须附加到具有相同 ID 的匹配 div。
HTML 分区
<div class="containerA" id='text b'></div>
<div class="containerA" id='text a'></div>
JavaScript
var myArray = [
a = {
text: 'text a',
comment: 'comment a'
},
b = {
text: 'text b',
comment: 'comment b'
},
c = {
text: 'text a',
comment: 'comment c'
},
d = {
text: 'text a',
comment: 'comment d'
},
e = {
text: 'text b',
comment: 'comment e'
}
];
for (var i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
var row = myArray[i];
console.log(row.text);
var textRef = row.text;
var commentsText = row.comment;
console.log(commentsText);
}
var myContainer = document.getElementsByClassName('containerA');
for (var i = 0; i < myContainer.length; i++) {
console.log(myContainer[i].attributes[1].nodeValue);
var idRef = myContainer[i].attributes[1].nodeValue;
}
最佳答案
试试这个:
myArray.forEach( function(item){
document.getElementById( item.text ).innerHTML = item.comment;
});
如果要求是每次都追加而不是提供新文本:
myArray.forEach( function(item){
var newestComment = document.createTextNode( item.comment );
document.getElementById( item.text ).appendChild( newestComment );
});
关于javascript - 将返回数据中的文本动态添加到具有匹配 id 的 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42351867/