如何使用选择菜单和 link_to 重定向到另一个页面 - Ruby on Rails
我想使用选择菜单重定向到另一个页面,但是当我选择“主页”时,它不会将我重定向到主页。什么也没发生...
<select>
<option>Select a menu</option>
<option><%= link_to 'Home', '/' %></option>
</select>
谢谢你的帮助。
I want to use a select menu to redirect to another page but when I select 'Home' it doesn't redirect me to the main page. Nothing happens...
<select>
<option>Select a menu</option>
<option><%= link_to 'Home', '/' %></option>
</select>
Thank you for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能将链接放入 SELECT 标记内。这是 HTML 的限制,而不是 Rails 的限制。
相反,您应该做的是这样的:
然后您需要确保在选择新链接时加载页面。这可以通过 jQuery 使用类似以下内容来完成:
当表单选择更改时,将加载新的 URL。
You can't put a link inside a SELECT tag. This is a limitation of HTML, not Rails.
What you should do instead is something like this:
Then you need to ensure that when the new link is selected, the page is loaded. This can be done with jQuery using something like this:
When the form selection is changed, the new URL is loaded.
link_to
帮助器输出一个 HTML 超链接,当嵌套在option
元素中时,该超链接将不起作用。您应该更改您的选项,使其具有以下格式:然后您可以使用一些 JavaScript 来观察下拉列表的
onchange
事件,并将document.location.href
设置为所选选项的值。这将执行重定向。或者,您可以在提交表单的下拉列表旁边有一个Go提交按钮,然后让Rails使用
redirect_to 帮手。
The
link_to
helper outputs an HTML hyperlink which is not going to work when nested within anoption
element. You should change your options so that they have this format:Then you could have some JavaScript that observes the
onchange
event of the dropdown and sets thedocument.location.href
to the value of the selected option. This will perform the redirect.Alternatively, you could have a Go submit button next to the dropdown that submits the form and then have Rails perform a server-side redirect to the page for the selected option using the
redirect_to
helper.这也将起作用:
This will also work: