【问题标题】:Text Field Tag Placeholder Returning As Value文本字段标记占位符作为值返回
【发布时间】:2012-11-09 00:55:36
【问题描述】:

我有一个表格,表格里面有一个 text_field_tag。是这样写的……

<%= text_field_tag "search",  :placeholder => 'Enter search term...' %>

但是,当生成 HTML 时,它会在页面源中返回...

<input id="search" name="search" type="text" value="{:placeholder=&gt;&quot;Enter search 
term...&quot;}" />

为什么要这样做,我该如何修复它以使占位符起作用?

【问题讨论】:

    标签: html css ruby-on-rails ruby-on-rails-3 placeholder


    【解决方案1】:

    text_field_tag 的第二个参数是值。给它 nil 让它为空:

    <%= text_field_tag "search", nil, :placeholder => 'Enter search term...' %>
    

    并给它一个字符串以具有默认值:

    <%= text_field_tag "search", 'Enter search term...' %>
    

    添加一个 onclick 事件以使用 jQuery 清空它:

    <%= text_field_tag "search", 'Enter search term...', :onclick => 'if($(this).val()=="Enter search term..."){$(this).val("");};' %>
    

    2016 年编辑:

    如今,大多数浏览器现在都支持HTML 5 placeholder,这使我们能够以更简洁的方式做到这一点:

    <%= text_field_tag 'search', nil, placeholder: 'Enter search term' %>
    # which produces the following HTML:
    <input type="text" value="" placeholder="Enter search term">
    

    jsFiddle link

    【讨论】:

    • 我犯了一个愚蠢的错误。谢谢。
    • 不客气 :) 你能看看我的帖子作为答案吗?
    • 是的,对不起。当我在玩一些 CSS 并分心时,我正打算这样做。
    • 这在 rails 5 中不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 2013-03-04
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    相关资源
    最近更新 更多