【问题标题】:Commas Appearing in Javascript rendered HTML出现在 Javascript 呈现的 HTML 中的逗号
【发布时间】:2018-09-13 13:45:50
【问题描述】:

我正在使用 Javascript 和 Contentful 渲染 HTML。

我的代码:

contentfulClient.getEntries({
   content_type: PRODUCT_CONTENT_TYPE_ID,
   order: '-fields.dateRated'
})
.then(function(entries) {
   container.innerHTML = renderProducts(entries.items)
})

function renderProducts(products) {
   return '<table id="film-table"><tr><th>Name</th><th>Rating</th></tr><tr><td>Check back tomorrow</td><td class="rating-cell">????</td></tr>' +
   products.map(renderSingleProduct) +
   '</table>'
}

但是,当我对此进行测试时,每个条目的表格上方都会出现一个逗号: commas above table.

感谢您的帮助。

【问题讨论】:

  • 你能用 plunker/JSfiddle/codepen 创建一个工作代码 sn-p 吗?
  • 您正在添加products.map(renderSingleProduct),它是一个数组,而不是任何表格单元格之外的字符串
  • 我有一个条目数组,每个条目都是表中的一行。逗号出现在表格之前,这就是我感到困惑的原因。

标签: javascript html contentful


【解决方案1】:

这里的问题是.map 函数返回一个数组。因此,当您将products.map(renderSingleProduct) 添加到现有字符串时,它会将这个数组转换为一个字符串,其中包含, 作为分隔符。

如果您在最后添加 .join('') 调用,一切都应该没问题,因为这会将数组重新转换为带有提供的分隔符的字符串。

function renderProducts(products) {
   return '<table id="film-table"><tr><th>Name</th><th>Rating</th></tr><tr> 
          <td>Check back tomorrow</td><td class="rating-cell">?</td></tr>' 
            +
            products.map(renderSingleProduct).join('') +
          '</table>'
          }

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2017-03-09
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多