在rails中动态添加div

时间:2015-03-07 16:35:03

标签: javascript jquery ruby-on-rails

我想要制作<div class="row">.

如果<div class="col-md-4">是三个或更多, 我想要制作<div class="row">.

因为我使用twitter bootstrap网格视图。

我的观点是

  <% @account_products.order(created_at: :desc).each do |product| %>
    <div>
      <div class="col-md-4">
          <div = "icons-right">
            <span class = "icons-right">
              <%= link_to image_tag("like.png", size: "30"),
                  line_items_path(product_id: product),
                 :class => "cart_image", method: :post %>

              <button class="btn btn-default btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false">
                <span class="caret"></span>
              </button>
              <ul class="dropdown-menu" role="menu">
                <!-- edit_product_path, product.id로 했으나 id값을 전달하지 않았다.  ->  전달은 매개변수로 ! -->
                <li role="presentation"><%= link_to "edit", edit_product_path(product.id) %></li>
                <li role="presentation"><%= link_to "destory", product, method: :delete %></li>
              </ul>
            </span>
          </div>

          <div class="fixed-size-image">
            <a href = "<%= product.image_url %>" target = "blank" > 
                <%= image_tag(product.item.url) if product.item? %>     
            </a>
          </div>

          <div class = "brand">
            <%= product.brand %>
          </div>

          <div class = "description">
            <%= product.title %>
          </div>

          <div class = "price">
            <%= product.price %>

          </div>

          <!-- line_item_path -> line_items_path    class="btn btn-primary btn-lg active -->
          <!-- like.png -->
      </div>
    </div>
  <% end %>

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你会尝试为每三列输出<div class="row">,是吗?

有两种方法可以做到:

<% @account_products.order(created_at: :desc).each_with_index do |product, i| %>
  <% if i%3 == 0 %>
    <div class="row">
  <% end %>
    ... (The rest of your code)
  <% if i%3 == 0 %>
    </div>
  <% end %>
<% end %>

或者:

<% @account_products.order(created_at: :desc).in_groups_of(3) do |product_group| %>
  <div class="row">
    <% product_group.compact.each do |product| %>
    ... (The rest of your code)
    <% end %>
  </div>
<% end %>

--- ---编辑

根据要求,jQuery解决方案:

var a = $('.col-md-4'); 
while(a.length) { 
  $(a.splice(0,3)).wrapAll("<div class='row' />")
}