【问题标题】:How to add HTML5 auto focus to a rails form?如何将 HTML5 自动对焦添加到 Rails 表单?
【发布时间】:2014-09-25 22:42:48
【问题描述】:

我有一个文本字段

  = text_field_tag('search_text_1', params[:search_text],
    options = {:type => 'search'} )

生成

<input id="search_text" name="search_text_1" type="search">

我想添加 HTML5 自动对焦,如

  = text_field_tag('search_text_1', params[:search_text], 
    options = {:type => 'search', :autofocus => true} )

这会生成

<input autofocus="autofocus" id="search_text" name="search_text_1" type="search">

这确实有效,但我怎样才能获得autofocus 的实际 HTML 输出,如 HTML 规范所示,即

<input autofocus id="search_text" name="search_text_1" type="search" autofocus>
# Not sure where it goes or if that matters

使用

options = {:type => 'search', :autofocus } 

给予

.../_search.html.haml:2: syntax error, unexpected '}', expecting => 
...:type => 'search', :autofocus } )

正如https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input 的 HTML5 规范所说,“这是一个布尔值”

【问题讨论】:

标签: ruby-on-rails ruby html autofocus


【解决方案1】:

如果您愿意修补私有 Rails 方法,则可以实现所需的输出。 Rails 用boolean_tag_option method in the TagHelper module 写出布尔属性,生成autofocus='autofocus' 格式。

如果您将以下内容添加到初始化程序,您可以将此方法替换为以最小化格式写出属性的方法。

module ActionView::Helpers::TagHelper
  private def boolean_tag_option(key)
    key
  end
end

显然,在升级应用程序使用的 Rails 版本时需要小心。这个方法目前看来还算稳定,4.2.0.beta.1master 中还是有的。

【讨论】:

    【解决方案2】:

    我最终选择了

    = text_field_tag('search_text_1', 
      params[:search_text], 
      options = {:type => 'search', :autofocus => true })
    

    并接受autofocus='autofocus'的输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多