【问题标题】:Javascript - loop to create list of cardsJavascript - 循环创建卡片列表
【发布时间】:2021-07-28 11:42:09
【问题描述】:

HTML 和简单的 JS(没有 react/vue)。 我需要做一个卡片列表,并想做一个循环以避免重复 html。

我当前的代码:

<div id="products-cards-container">
    <div class="products-cards">              
        <div class="product-header">
            <img src="../assets/img/image1.png"/>
        </div>
        <div class="product-content">
            <h4>title 1</h4>
            <p>super content 1</p>
        </div> 
        <button class="info-button">+ info</button>
    </div>
    <div>
        <div class="product-header">
            <img src="../assets/img/cards/products/image2.png"/>
        </div>
        <div class="product-content">
            <h4>title 2</h4>
            <p>super content 2</p>
        </div> 
        <button class="info-button">+ info</button>
    </div>
    <div>
        <div class="product-header">
            <img src="../assets/img/cards/products/image-3.png"/>
        </div>
        <div class="product-content">
            <h4>title 3</h4>
            <p>blablablablbalbalbabla blablaba</p>
        </div> 
        <button class="info-button">+ info</button>
    </div>\
</div>

我正在尝试返回 html

script.js

const valuesCards = [
    { 
    image: '../img/image1.png', 
    title: 'title 1', 
    content: 'super content 1',
    },
    {
    image: '../img/image2.png', 
    title: 'title 2', 
    content: 'super content 2'
    },
    { 
    image: '../img/image-3.png', 
    title: 'title3', 
    content: 'blablablablbalbalbabla blablaba'
    },
   ]

创建一个在 .products-cards div 中插入卡片列表的函数:

    function returnCards() => {
    ----- AND HERE I AM STUCK
   (as well, all tries I did with a simple array / object returned only the last info) ----
    }

【问题讨论】:

    标签: javascript arrays loops object components


    【解决方案1】:

    您需要执行一个“for 循环”来迭代您的 valuesCards 对象,并为每个值返回一个 html 模板并注入到 DOM 中所需的元素中。

    例如:

        // Define the object
        const valuesCards = [
          {
            'image': '../img/image1.png',
            'title': 'title 1',
            'content': 'super content 1',
          },
          {
            'image': '../img/image2.png',
            'title': 'title 2',
            'content': 'super content 2'
          },
          {
            'image': '../img/image-3.png',
            'title': 'title3',
            'content': 'blablablablbalbalbabla blablaba'
          }
        ]
        
        // Identify the DOM element to store cards
        cardsContainer = document.querySelector('#products-cards-container');
        
        // Create a loop that iterates over valuesCards object
        for (let value of Object.values(valuesCards)) {
          console.log(value.title);
            // Create an element to store new card content
            let newCard = document.createElement('DIV');
        
            // Add products-cards class to new element
            newCard.classList.add('products-cards');
        
            // Create a multiline string template with current values each time 
            cardHtml = `
               <div class="">              
                <div class="product-header">
                    <img src="${value.image}"/>
                </div>
                <div class="product-content">
                    <h4>${value.title}</h4>
                    <p>${value.content}</p>
                </div> 
                <button class="info-button">+ info</button>
               </div>   
            `;
        
            // Append the new element to the cardsContainer element in DOM
            cardsContainer.appendChild(newCard);
        
            // Inject the template html on DOM's new append item
            newCard.innerHTML = cardHtml;
        
        }
    

    重要!!在要打印卡片的 html 中创建一个 id="products-cards-container" 的 div 元素。

    【讨论】:

    • Todavia no aparece nada。 el documento donde pongo tu codigo se llama cards-content.js y no hay nada más que este codigo que me has dado。 De momento importo así en mi documento html : 。测验重要吗?
    • 我对我的代码进行了一些更改并在本地进行了测试。现在它应该可以工作了。 .
    【解决方案2】:

    你可以这样做

    const valuesCards = [
        { 
        image: '../img/image1.png', 
        title: 'title 1', 
        content: 'super content 1',
        },
        {
        image: '../img/image2.png', 
        title: 'title 2', 
        content: 'super content 2'
        },
        { 
        image: '../img/image-3.png', 
        title: 'title3', 
        content: 'blablablablbalbalbabla blablaba'
        },
       ];
       
       let cardHTML = '';
       valuesCards.map(element => {
            cardHTML += '<div> \
            <div class="product-header"> \
             <img src="'+element.image+'"/> \
            </div> \
            <div class="product-content"> \
               <h4>'+element.title+'</h4> \
             <p>'+element.content+'</p> \
            </div> \
            <button class="info-button">+ info</button> \
          </div> \
          ';
       });
       
    document.getElementsByClassName('products-cards')[0].innerHTML = cardHTML;
     <div id="products-cards-container">
           <div class="products-cards"> 
             
           </div>
    </div>

    【讨论】:

      【解决方案3】:

      使用Array.prototype.map 函数和模板文字。

      const container = document.getElementById('products-cards-container');
      const valuesCards = [{
          image: '../img/image1.png',
          title: 'title 1',
          content: 'super content 1',
        },
        {
          image: '../img/image2.png',
          title: 'title 2',
          content: 'super content 2'
        },
        {
          image: '../img/image-3.png',
          title: 'title3',
          content: 'blablablablbalbalbabla blablaba'
        },
      ]
      
      function returnCards(valuesCards) {
        return "<div class=\"products-cards\">" + valuesCards.map(valuesCard => `
        <div>
          <div class="product-header">
            <img src="${valuesCard.image}"/>
          </div>
          <div class="product-content">
            <h4>${valuesCard.title}</h4>
            <p>${valuesCard.content}</p>
          </div> 
          <button class="info-button">+ info</button>
        </div>`).join('') + "</div>";
      }
      
      container.innerHTML = returnCards(valuesCards);
      &lt;div id="products-cards-container"&gt;&lt;/div&gt;

      【讨论】:

        【解决方案4】:

        const valuesCards = [
            { 
            image: '../img/image1.png', 
            title: 'title 1', 
            content: 'super content 1',
            },
            {
            image: '../img/image2.png', 
            title: 'title 2', 
            content: 'super content 2'
            },
            { 
            image: '../img/image-3.png', 
            title: 'title3', 
            content: 'blablablablbalbalbabla blablaba'
            },
           ]
        valuesCards.map(card=> {
          var cardDiv = document.createElement('div');
          cardDiv.innerHTML = `
                        <div class="product-header">
                          <img src="${card.image}"/>
                        </div>
                        <div class="product-content">
                          <h4>${card.title}</h4>
                          <p>${card.content}</p>
                        </div> 
                        <button class="info-button">+ info</button>`
          document.getElementsByClassName('products-cards')[0].appendChild(cardDiv);
        })
        <div id="products-cards-container">
               <div class="products-cards">  
                  </div>
        </div>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-06-19
          • 2020-07-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多