【问题标题】:array.foreach not working inside append in jquery [duplicate]array.foreach 在 jquery 中的 append 内不起作用 [重复]
【发布时间】:2021-10-21 15:30:28
【问题描述】:

我无法显示未定义的图像数组

这是我的代码:

  data.rows.forEach(function (row) {
    var attachments = JSON.parse(row.attachment);

    $("#records_row").append(
      "<tr>\
        <td>" +row.id +"</td>\
        <td>" + row.subject +"</td>\
        <td id='imagecol'>"+
          attachments.forEach(item => {
            "<img src='"+item+"' class='img-thumbnail'>" //This part is showing undefined
          })
          +"</td>\
       </tr>"
    );

  });

我的数组

(2) ['/images/footer-bg.jpg', '/images/hero-bg.jpg']

【问题讨论】:

  • 请提供data的数组
  • 看起来你需要item 而不是attachments[0]
  • 上面有两个单独的问题: 1. 调用forEach 的结果是总是 undefined (more)。您可能想要map(然后.join("") 从结果数组中创建一个字符串)。 2.你的回调函数doesn't return anything.
  • 谢谢 T.J.克劳德,这解决了我的问题。

标签: jquery


【解决方案1】:
var img = ""
attachments.forEach(item => {
            img += "<img src='"+attachments[0]+"' class='img-thumbnail'>" 
          })

array.forEach 没有返回值

【讨论】:

    【解决方案2】:

    Here is example for data with forEach

    var data = [{
    'attachment':'attachment',
    'id':'id',
    'subject':'subject'
    },{
    'attachment':'attachment',
    'id':'id',
    'subject':'subject'
    },{
    'attachment':'attachment',
    'id':'id',
    'subject':'subject'
    }]
    
    data.forEach(function (row) {
       console.log(row);
      });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      • 2010-10-18
      相关资源
      最近更新 更多