javascript - 将返回数据中的文本动态添加到具有匹配 id 的 div 中

标签 javascript jquery arrays html

首先,我仍然是一个新手,仍在学习,我已经学到了很多东西,并希望在我继续这段旅程时继续学习。 好的,所以我有以下代码并尝试将数组对象附加到具有匹配 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/

相关文章:

php - 在保留键的同时反转数组值

javascript - 在网络浏览器上显示 html 页码

javascript - Angularjs:Html 呈现为文本

javascript - 使用 http.request 时 Nodejs 性能如何扩展?

php - PayPal 购买转到 2 个不同的 paypal 帐户

javascript - 当两者实现相同的目标时,编写此代码的首选方法是什么?

jquery - 在滚动条上运行 jQuery 数字计数器

objective-c - 如何从表数据源访问数组?

java - 在二维数组中获取空​​格分隔的行输入

javascript - 在手机上测试时文本隐藏在图表 js 中