【问题标题】:How to add a class to a select dropdown loop using ERB如何使用 ERB 将类添加到选择下拉循环
【发布时间】:2016-09-17 18:34:35
【问题描述】:

我有以下循环来使用 ERB 创建一个选择下拉列表。它工作正常。

  <%= f.select(:player_id) do %>
    <% @players.each do |p| %>
      <%= content_tag(:option, "#{p.first_name} #{p.last_name}", value: p.id) %>
    <% end %>
  <% end %>

我的问题是如何向选择元素添加一个类?

我尝试了以下方法:

<%= f.select(:player_id), class: "form-control" do %>
    <% @players.each do |p| %>
      <%= content_tag(:option, "#{p.first_name} #{p.last_name}", value: p.id) %>
    <% end %>
<% end %>

<%= f.select(:player_id), { class: "form-control" } do %>
    <% @players.each do |p| %>
      <%= content_tag(:option, "#{p.first_name} #{p.last_name}", value: p.id) %>
    <% end %>
<% end %>

我见过类似的问题,但没有一个像上面的例子那样使用循环。

【问题讨论】:

  • 尝试 JavaScript 为 select 元素添加类,如 $(your_select_element).addClass('.your-class-name')
  • 我想过这个,但如果可能的话,我更喜欢内联。

标签: html css ruby-on-rails ruby-on-rails-4 erb


【解决方案1】:

这应该适合你。

<%= f.select :player_id, options_for_select( @players.collect { |player| ["#{player.first_name} #{player.last_name}", player.id] } ), class: 'form-control' %>

【讨论】:

  • 不太好用,但让我找到了我想要的东西
【解决方案2】:

这就是我最终做的:

<%= f.select :player_id, options_for_select( @players.collect { |player| ["#{player.first_name} #{player.last_name}", player.id] } ), {}, { class: 'form-control' } %>

【讨论】:

    【解决方案3】:

    我认为你的代码有问题是f.select(:player_id)

    您调用的 select 方法只有一个参数:player_id。所以你可以像这样传递其他选项。

    <%= f.select :player_id, class: "form-control" do %>
      <% @players.each do |p| %>
        <%= content_tag(:option, "#{p.first_name} #{p.last_name}", value: p.id) %>
      <% end %>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 2011-12-28
      • 2016-02-08
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 2017-06-15
      相关资源
      最近更新 更多