【问题标题】:Insert one css class to select on Rails date_select在 Rails date_select 上插入一个 CSS 类以进行选择
【发布时间】:2012-04-05 15:21:22
【问题描述】:

我正在使用 date_select 方法生成 3 个 html 选择,即日、月和年。 但我需要每个选择都有一类 CSS。

我在文档中没有找到如何将参数传递给助手,我尝试了几种方法,但没有任何结果。

导轨视图:

<%= f.date_select :birthday, :order => [:day, :month, :year], :start_year => 1910, :end_year => 2012, :html => {:class => ['day', 'month', 'year']} %>

HTML 输出:

<select id="poll_user_birthday_3i" name="poll_user[birthday(3i)]">
<select id="poll_user_birthday_2i" name="poll_user[birthday(2i)]">
<select id="poll_user_birthday_1i" name="poll_user[birthday(1i)]">

像我一样输出HTML:

<select id="poll_user_birthday_3i" name="poll_user[birthday(3i)]" class="day">
<select id="poll_user_birthday_2i" name="poll_user[birthday(2i)]" class="month">
<select id="poll_user_birthday_1i" name="poll_user[birthday(1i)]" class="year">

谢谢!

【问题讨论】:

    标签: ruby-on-rails html-helper ruby-on-rails-3.2


    【解决方案1】:

    我解决这个问题的方法是使用 css

    查看

    <span class="datetime"> <%= f.date_select :birthdate, :order => [:day, :month, :year], :start_year => 1910, :end_year => 2012 %></span>
    

    CSS

    .datetime select:nth-child(1){
      width: 130px;
      text-indent: 15px; 
    }
    
    .datetime select:nth-child(2) {
      width: 200px;
      text-indent: 5px;
    }
    
    .datetime select:nth-child(3) {
      width: 110px;
      text-indent: 15px;
    }
    

    【讨论】:

    • rails 坏了...我们将在 css 中修复它:shipit:
    【解决方案2】:

    Rails 现在确实可以满足 OP 的要求。

    :with_css_classes - 如果要为“选择”标签分配不同的样式,请设置为 true。此选项会自动为您的“选择”标签设置“年”、“月”、“日”、“小时”、“分钟”和“秒”类。

    Source

    【讨论】:

    • *问题是针对 date_select,但推理适合 datetime_select。 * 这可能是最好的general case 答案,尽管 rails 仍然会为 datetime_select 添加破折号和冒号,然后事情就会变得一团糟。如果你使用&lt;div,为了得到一些不错的布局,将日期数据设置为`float:left; ` 不要将浮点数分配给小时,然后将float: right; 分配给分钟。如果所有字段不占用 div 宽度的 100%,则破折号和冒号将就位。
    【解决方案3】:

    不幸的是,date_select 没有提供将不同的 html 选项传递给每个选择的方法。可选的html_options 参数应用于它们中的每一个。

    您可以使用单独的助手 select_day select_hourselect_minute 来编译您自己的。

    这样您就可以将单独的类传递给每个类。

    【讨论】:

      【解决方案4】:

      根据rails文档(http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-date_select),方法定义如下。

      date_select(object_name, method, options = {}, html_options = {})

      使用上述选项,您可以指定您的代码,如下所示。

           <%= f.date_select :birthday, {:order => [:day, :month, :year], :start_year => 1910, :end_year => 2012}, {:class => 'common-class'} %>
      

      您传递的 html 选项将被丢弃,因为它没有按照文档进行,因此您无法在 date_select 中应用任何类。

      您可以参考以下主题了解更多信息。

      How do I set the HTML options for collection_select in Rails?

      此外,您需要按照 lebreeze 的建议编写单独的辅助方法并应用上述步骤以获得准确的输出。

      希望对你有帮助。

      【讨论】:

      • 谢谢。它有很大帮助! start&end_year 功能也非常有用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      相关资源
      最近更新 更多