Rails:link_to 图像标签.如何将类添加到标签

问题描述:

我正在使用如下所示的 link_to img 标签

I am using link_to img tag like following

<%= link_to image_tag("Search.png", :border=>0, :class => 'dock-item'), 
:action => 'search', :controller => 'pages'%><span>Search</span></a>

导致以下 html

<a href="/pages/search"><img alt="Search" border="0" class="dock-item" 
src="/images/Search.png?1264132800" /></a><span>Search</span></a> 

我希望 class="dock-item" 转到 <a> 标签而不是 img 标签.

I want the class="dock-item" to go to the <a> tag instead of the img tag.

我该如何更改?

更新:

<%= link_to image_tag("Search.png", :border=>0), :action => 'search', 
:controller => 'pages', :class => 'dock-item' %>

结果

<a href="/pages/search?class=dock-item"><img alt="Search" border="0" 
src="/images/Search.png?1264132800" /></a> 

你可以试试这个

link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, {class: 'dock-item'}

甚至

link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, class: 'dock-item'

注意花括号的位置非常重要,因为如果你错过了它们,rails 会假设它们形成一个单一的散列参数(阅读更多关于这个 这里)

note that the position of the curly braces is very important, because if you miss them out, rails will assume they form a single hash parameters (read more about this here)

并根据 api for link_to:

link_to(name, options = {}, html_options = nil)

  1. 第一个参数是要显示的字符串(也可以是 image_tag)
  2. 第二个是链接的url参数
  3. 最后一项是用于声明 html 标签的可选参数,例如类、onchange 等

希望有帮助!=)