Rails 中的 link_to 方法和单击事件 [英] link_to method and click event in Rails

查看:27
本文介绍了Rails 中的 link_to 方法和单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建这种类型的链接:

How do I create a link of this type:

<a href="#" onclick="document.getElementById('search').value=this.value">

在 Rails 中使用方法 link_to?

using method link_to in Rails?

我无法从 Rails 文档中弄清楚.

推荐答案

您可以使用 link_to_function(在 Rails 4.1 中移除):

You can use link_to_function (removed in Rails 4.1):

link_to_function 'My link with obtrusive JavaScript', 'alert("Oh no!")'

或者,如果您绝对需要使用 link_to:

Or, if you absolutely need to use link_to:

link_to 'Another link with obtrusive JavaScript', '#',
        :onclick => 'alert("Please no!")'

但是,将 JavaScript 直接放入生成的 HTML 中是突兀,并且是不好的做法.

However, putting JavaScript right into your generated HTML is obtrusive, and is bad practice.

相反,您的 Rails 代码应该是这样的:

Instead, your Rails code should simply be something like this:

link_to 'Link with unobtrusive JavaScript',
        '/actual/url/in/case/javascript/is/broken',
        :id => 'my-link'

假设您使用的是 Prototype JS 框架,这样的 JS 在您的 application.js:

And assuming you're using the Prototype JS framework, JS like this in your application.js:

$('my-link').observe('click', function (event) {
  alert('Hooray!');
  event.stop(); // Prevent link from following through to its given href
});

或者如果您使用的是 jQuery:

Or if you're using jQuery:

$('#my-link').click(function (event) {
  alert('Hooray!');
  event.preventDefault(); // Prevent link from following its href
});

通过使用这第三种技术,您可以保证链接将继续到其他页面——而不仅仅是无声地失败——如果 JavaScript 对用户不可用.请记住,JS 可能不可用,因为用户的互联网连接状况不佳(例如,移动设备、公共 wifi)、用户或用户的系统管理员禁用了它,或者发生了意外的 JS 错误(即开发者错误).

By using this third technique, you guarantee that the link will follow through to some other page—not just fail silently—if JavaScript is unavailable for the user. Remember, JS could be unavailable because the user has a poor internet connection (e.g., mobile device, public wifi), the user or user's sysadmin disabled it, or an unexpected JS error occurred (i.e., developer error).

这篇关于Rails 中的 link_to 方法和单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆