Ruby-on-rails 如何使按钮作为erb中的链接工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11985810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a button work as a link in erb?
提问by usr
<%= link_to 'New Post', new_post_path %>
This produces link to new_post_path. Previously i used <input type="submit" class="new" name="Addlist" value="Add New" />which resembled like a button. So how can i make the link look like button in erb?
这会产生指向new_post_path. 以前我用过<input type="submit" class="new" name="Addlist" value="Add New" />它,就像一个按钮。那么我怎样才能让链接看起来像 erb 中的按钮呢?
回答by Ryan Shih
Just to throw another option out there since I had a scenario where the button_to option didn't work. This looks kind of similar to that.
只是为了抛出另一个选项,因为我有一个 button_to 选项不起作用的场景。这看起来有点像那个。
<%= link_to '<button type="button">New Post</button>'.html_safe, new_post_path %>
What I basically wanted is a button that doesn't turn into a submit, since I have multiple buttons on the page that aren't related to a form, and I really just want it to just go to another page.
我基本上想要的是一个不会变成提交的按钮,因为我在页面上有多个与表单无关的按钮,我真的只想让它转到另一个页面。
回答by waldyr.ar
Take a look at button_to. In summary it will be simmilar to this:
看看button_to。总之,它将类似于:
<%= button_to "New Post", { :action => "new" }, :method => :get %>
Although be aware, this method accepts the :methodand :confirmmodifiers described in the link_todocumentation. If no :methodmodifier is given, it will default to performing a POSToperation. You can also disable the button by passing :disabled => truein html_options. If you are using RESTful routes, you can pass the :methodto change the HTTP verb used to submit the form.
尽管请注意,此方法接受文档中描述的:method和:confirm修饰符link_to。如果没有:method给出修饰符,它将默认执行一个POST操作。您也可以通过传递禁用按钮:disabled => true在html_options。如果您使用 RESTful 路由,您可以传递:method来更改用于提交表单的 HTTP 动词。
回答by nelsonic
@Ryan's answer is good but sadly failshtml validation http://validator.w3.org/
@Ryan 的回答很好,但遗憾的是未能通过html 验证http://validator.w3.org/
error: The element button must not appear as a descendant of the a element.
错误:元素按钮不得作为 a 元素的后代出现。
Why not simply apply a (CSS) classto your link and make it appearas a button.
为什么不简单地将 (CSS)类应用到您的链接并使其显示为按钮。
erb:
erb:
<%= link_to "Button Text", new_post_path, class: 'button' %>
<%= link_to "Button Text", new_post_path, class: 'button' %>
produces (valid& semantic) HTML:
产生(有效和语义)HTML:
<a class="button" href="/post/new">Button Text</a>
<a class="button" href="/post/new">Button Text</a>
which you can then styleto looklike a button.
然后您可以将其样式设置为看起来像一个按钮。

