将表行放入Rails中的链接

jha*_*amm 36 ruby-on-rails

我试图在表格链接到编辑页面.我知道链接正在创建,因为我可以将它们打印出来.我很接近,但我错过了一些重要的事情.我如何更改以使链接正常工作?

<h1>Scouts</h1>
<p><%= button_to "Add a new Scout", new_scout_path, :method => :get %></p>
<div class="message-board">
  <table>
    <tr>
      <th>Name</th>
      <th>Rank</th>
      <th>Advancement Date</th>
      <th>Age</th>
    </tr>  

<% @scouts.each do |scout| %>
    <tr <% link_to edit_scout_path(scout) %> >
      <td><%= scout.name %></td>
      <td><%= scout.rank %></td>
      <td><%= scout.advancement %></td>
      <td><%= scout.age %></td>
    </tr>
<% end %>
  </table>
</div>
Run Code Online (Sandbox Code Playgroud)

Rya*_*igg 66

正如罗宾所说,这是无效的HTML.你可能不应该这样做.

我个人会onclicktr使用jQuery 上发布一个事件.该tr元素是这样的:

<tr data-link="<%= edit_scout_path(scout) %>">
   ...
</tr>
Run Code Online (Sandbox Code Playgroud)

然后关联的JavaScript(放在诸如此类的文件中app/assets/javascripts/scouts.js)将是这样的:

$("tr[data-link]").click(function() {
  window.location = $(this).data("link")
})
Run Code Online (Sandbox Code Playgroud)

这将使所有tr具有data-link属性的元素像我们认为可能的最不显眼的方式一样充当URL.

  • 使用Rails 3.2.3和jquery-rails 2.0.2,我收到消息"this.data不是函数".将jQuery函数内容更改为`window.location = this.dataset.link`使其正常工作. (11认同)
  • 仅对我使用`window.location = $(this).data("link")` (8认同)
  • 我只是想出了[嵌入式按钮问题的一个hacky解决方案](https://gist.github.com/dideler/54a13598027658edeca4).我的按钮是一个链接(带有一些样式)并包含一个glyphicon.我指定窗口位置,除非事件目标是`a`或`i`元素.为什么那些元素?因为按钮由带有嵌套`i`元素的`a`元素组成,光标可以单击. (2认同)

Pra*_*wal 5

我是新手,我遇到了同样的问题,并使用了Ryan的建议以及随后的一些变化 -

$("tr").click(function() { window.location = $(this).data("link") })

你必须使用$(this).