首页 文章

插入一个css类以在Rails date_select上选择

提问于
浏览
7

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

我没有在文档中找到如何将参数传递给帮助器,我尝试了几种方法而没有 .

Rails查看:

<%= 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">

谢谢!

4 回答

  • 2

    他们解决这个问题的方式是用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;
    }
    
  • 8

    Rails现在确实做了OP想要的 .

    :with_css_classes - 如果要为“select”标记指定不同的样式,则设置为true . 此选项会自动为“选择”标记设置“年”,“月”,“日”,“小时”,“分钟”和“秒”等级 .

    Source

  • 3

    不幸的是, date_select 没有提供将不同的html选项传递给每个选项的方法 . 可选的 html_options 参数适用于每个参数 .

    您可以使用单独的帮助程序 select_day select_hourselect_minute 来编译自己的帮助程序 .

    这样,您可以将单独的类传递给每个类 .

  • 2

    根据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建议并应用上述步骤以获得准确的输出 .

    希望能帮助到你 .

相关问题