简体   繁体   English

Rails中的link_to方法和click事件

[英]link_to method and click event in Rails

How do I create a link of this type: 如何创建此类型的链接:

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

using method link_to in Rails? 在Rails中使用方法link_to

I couldn't figure it out from Rails docs . 我无法从Rails文档中弄清楚。

You can use link_to_function (removed in Rails 4.1): 您可以使用link_to_function (在Rails 4.1中已删除):

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

Or, if you absolutely need to use link_to : 或者,如果您绝对需要使用link_to

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

However, putting JavaScript right into your generated HTML is obtrusive , and is bad practice . 但是,将JavaScript正确地放入生成的HTML中是很麻烦的 ,而且是不明智的做法

Instead, your Rails code should simply be something like this: 相反,您的Rails代码应该只是这样的:

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

And assuming you're using the Prototype JS framework , JS like this in your application.js : 并假设您使用的是Prototype JS框架 ,那么JS在您的application.js

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

Or if you're using jQuery : 或者,如果您使用的是jQuery

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

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. 通过使用第三种技术,可以确保如果用户不可用JavaScript,则链接将继续进入其他页面,而不仅仅是无声地失败。 Remember, JS could be unavailable because the user has a poor internet connection (eg, mobile device, public wifi), the user or user's sysadmin disabled it, or an unexpected JS error occurred (ie, developer error). 请记住,由于用户的Internet连接不畅(例如,移动设备,公共wifi),用户或用户的sysadmin禁用了JS,或者发生了意外的JS错误(即,开发人员错误),因此JS可能不可用。

To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section... 要跟踪Ron的答案(如果使用JQuery并将其放在application.js或head部分中),则需要将其包装在ready()部分中...

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

只是使用

=link_to "link", "javascript:function()"

another solution is catching onClick event and for aggregate data to js function you can 另一个解决方案是捕获onClick事件,并将数据汇总到js函数中,您可以

.hmtl.erb .hmtl.erb

<%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>

.js .js

// handle my-class click
$('a.my-class').on('click', function () {
  var link = $(this);
  var array = link.data('array');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM