【问题标题】:Wrap every 4th product within a div将每 4 个产品包装在一个 div 中
【发布时间】:2015-03-17 19:45:58
【问题描述】:

我需要一点帮助。我正在构建自己的自定义 BigCartel 主题,但遇到了以下问题:目前我在产品主页面上列出了我的所有产品(它们并不多),并且我试图将每 4 个产品包装在一个分区。 基本上我有

<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>

我想要的最终结果是

<div class="wrap">
  <div class="product"></div>
  <div class="product"></div>
  <div class="product"></div>
  <div class="product"></div>
</div>
<div class="wrap">
  <div class="product"></div>
</div>

我不确定我应该如何使用他们的模板语言来做到这一点。

【问题讨论】:

  • 那么,你有什么问题?
  • @racecarjonathan 我不确定我应该如何使用他们的templating language
  • 下次您可能希望将其包含在您的帖子中...这是您遗漏的大量信息...我刚刚编辑了您的帖子以将其包含在您的帖子中
  • @racecarjonathan 谢谢伙计,这是有道理的。很抱歉!
  • 没问题...祝你好运!

标签: html bigcartel


【解决方案1】:

使用 jQuery:

var wraps = $('.wrap');
$('.products').each( function(e, i){
  wraps[Math.floor(i/4)].appendChild(e);
})

jQuery 将为所有产品返回一个列表 (HTMLCollection),迭代此列表,您可以将您的项目包装在 div 中,引用列表索引。

【讨论】:

  • 请为您的答案添加一些解释。
  • @mohmad-taher 感谢您的回复。但是,如果我尝试使用您的方法,我会收到以下错误 'Uncaught TypeError: Cannot read property 'appendChild' of undefined'
  • var wraps = $('wrap'); 应该是var wraps = $('.wrap');
  • @Seb 对不起拼写错误,将被修复
【解决方案2】:

使用template language,我认为可以这样做:

 <div class="wrap">

 {% for product in products.all %}
   <div class="product ">
     {{ product.name }} </div>
   {% if forloop.index % 4 == 0 %}
     </div>

     <div class="wrap">

   {% endif %}
 {% endfor %}

 </div>

【讨论】:

    【解决方案3】:

    我试着变得聪明一点。假设你有几个 .wrap 元素。

    var products = document.querySelectorAll('.products'), 
        wraps = document.querySelectorAll('wrap');
    [].forEach.call(products, function(e, i){
      wraps[Math.floor(i/4)].appendChild(e);
    })
    

    【讨论】:

      【解决方案4】:

      我意识到这个问题有点老了,但我发现接受的答案不起作用。

      这就是我让它在模板语言中工作的方式(有点像?Liquid):

      {% for product in products %}
      
        {% assign zeroindexmodfour = forloop.index0 | modulo: 4  %}
        {% assign indexmodfour = forloop.index | modulo: 4  %}
      
        {% if zeroindexmodfour == 0 %}
          <div class="wrap">
        {% endif %}
      
        <div class="product"></div>
      
        {% if indexmodfour == 0 or forloop.last %}
          </div>
        {% endif %}
      
      {% endfor %}
      

      【讨论】:

        猜你喜欢
        • 2011-03-22
        • 1970-01-01
        • 1970-01-01
        • 2014-10-31
        • 2013-03-03
        • 1970-01-01
        • 1970-01-01
        • 2014-08-30
        • 2014-01-22
        相关资源
        最近更新 更多