【问题标题】:how to loop through the contentful data within javascript and display in bootstrap grid columns?如何遍历 javascript 中的内容数据并在引导网格列中显示?
【发布时间】:2020-12-02 02:54:53
【问题描述】:

我正在开发 Contentful CMS,用于发布一些数据并在 html 页面中检索它。我使用 JavaScript 在引导网格列中显示这些内容,但无法正确显示数据。

这是我的代码:

     <div class="row justify-content-center">
            <div id="content"></div>
       </div>

      var client = contentful.createClient({
      space: '#######',
       accessToken: '#######'
     })

 var container = document.querySelector('#content');

  client.getEntries()
  .then(function(entries) {
    container.innerHTML = renderProducts(entries.items)
  })


function renderProducts(products) {
    products.map(function(product) {
        console.log(product.fields)
        return  '<div class="col-lg-4 col-md-6">' +
            '<a href="service-details.html" class="single-feature wow fadeInUp">' +
                '<img src="assets/images/icon/064-vector.png" alt="">' +
                '<div class="content">' +
                    '<h4 class="title">' +
                        '<p>cool</p>' +
                    '</h4>'+ 
                '</div>' +
            '</a>' +
      '</div>'
  })
}

它在控制台中正确显示数据,但 HTML 没有按照我想要的方式呈现。

【问题讨论】:

    标签: javascript html contentful


    【解决方案1】:

    嘿嘿。我没有测试我可以看到两个潜在的问题。 renderProducts 没有返回任何东西。您可以尝试更改它以返回您映射的products。然后innerHTML 需要一个字符串值,这意味着您必须将映射数组连接在一起。

    function renderProducts(products) {
        //?add a return here
        return products.map(function(product) {
            console.log(product.fields)
            return  '<div class="col-lg-4 col-md-6">' +
                '<a href="service-details.html" class="single-feature wow fadeInUp">' +
                    '<img src="assets/images/icon/064-vector.png" alt="">' +
                    '<div class="content">' +
                        '<h4 class="title">' +
                            '<p>cool</p>' +
                        '</h4>'+ 
                    '</div>' +
                '</a>' +
          '</div>'
      }).join('');
      // ? join the array of strings together to one long string
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      • 2015-01-05
      • 2018-09-29
      • 1970-01-01
      • 2011-10-28
      相关资源
      最近更新 更多