首页 > 解决方案 > ruby 上的 rails 循环顺序不正确,不在 td 中的行出现在顶部

问题描述

我已经搜索了这个问题,但无法找到答案,所以我想我会问。

我有一个 ActiveRecord 对象被一个 .each 循环,以生成一个表,其中每条记录都有一行。现在我试图在循环的底部放置一个 div,以便可以使用 javascript 在每条记录下添加更多行。问题是,除非 div 在标签内(虽然它只需要在 a 内),否则它们都会在循环的其余输出之上,如下所示:

<div>
</div>
<div>
</div>
<tr>
</tr>
<tr>
</tr>

然后在div应该去的底部有一个空的,但它是空的

它应该是

<tr>
</tr>
<tr>
<div>
</div>
</tr>

这是我的观点,我所指的 div 靠近底部。

感谢您的任何帮助。

            <div class="collapse" id=<%="searchExpand#{@count}"%> >
                <div class="card card-body">
                    Loading
                </div>
            </div>

<%= link_to 'Download CSV', "/collator/#{@file_name}" %>
<h1>In show, <%= @search_id %> status code <%= @status_code %> </h1>
<h4> <%= @used_keywords.any? ? "Searched previously: #{@used_keywords}" : " These words have been searched for #{@used_keywords}" %> </h4>
    <%= @keywords %>
<table class="table">
    <thead>
        <tr>
            <th scope="col">Keyword</th>
        <!--    <th scope="col">Title</th> -->
            <th scope="col">Shipper</th>
            <th scope="col">Cosignee</th>
            <th scope="col">Origin</th>
            <th scope="col">Destination</th>
            <th scope="col">Date</th>
            <th scope="col">Expand</th>

        </tr>
    </thead>
    <tbody>
        <%@count = 1; previous_keyword = "" %>
        <% @shipment_records.each do |shipment| %>
            <tr>
                <th scope="row"><a href=<%= "xxx/{shipment.url}" %> target ="_blank"><%="#{@count}" %> </a> </th>

                <td><%= shipment.shipper %></td>
                <td><a href=<%="https://www.google.com/search?q=#{CGI.escape(shipment.consignee)}"%> target="_blank"><%= shipment.consignee %></a></td>
                <td><%= shipment.origin %></td>
                <td><%= shipment.destination %></td>
                <td><%= shipment.date %></td>
                <td><button class="btn btn-primary" type="button" onclick="searchExpand(<%="'searchExpand#{@count}','#{shipment.consignee}'"%>);"data-toggle="collapse" data-target=<%="#searchExpand#{@count}"%> aria-expanded="false" aria-controls="searchExpand" >Deep Search</button></td>
                </tr>
                <tr>
                <div class="collapse" id=<%="searchExpand#{@count}"%> >
                    <div class="card card-body">
                        Loading
                    </div>
                </div>
                </tr>
            <% @count +=1 %>

        <% end %>


    </tbody>
</table>

标签: htmlruby-on-railsloopshtml-table

解决方案


a的允许内容<tr>是:

零个或多个<td>和/或<th>元素;脚本支持元素 (<script><template>) 也是允许的

所以像这样的结构:

<tr>
  <div>...</div>
</tr>

不是有效的 HTML,浏览器会将其重写为有效的,这就是为什么事情在你身上移动的原因。

解决方案是使用有效的 HTML,更像是:

<tr>
  <td colspan="7">
    <div class="collapse" id=<%="searchExpand#{@count}"%> >
      <div class="card card-body">
        Loading
      </div>
    </div>
  </td>
</tr>

然后调整您的 JavaScript 以正确处理新的<td>.


推荐阅读