link_to method and click event in Rails

后端 未结 4 1313
执念已碎
执念已碎 2020-12-22 16:53

How do I create a link of this type:


using method

相关标签:
4条回答
  • 2020-12-22 16:58

    just use

    =link_to "link", "javascript:function()"
    
    0 讨论(0)
  • 2020-12-22 16:59

    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...

    $(document).ready(function() {
      $('#my-link').click(function(event){
        alert('Hooray!');
        event.preventDefault(); // Prevent link from following its href
      });
    });
    
    0 讨论(0)
  • 2020-12-22 17:03

    You can use link_to_function (removed in 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 'Another link with obtrusive JavaScript', '#',
            :onclick => 'alert("Please no!")'
    

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

    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'
    

    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
    });
    

    Or if you're using 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. 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).

    0 讨论(0)
  • 2020-12-22 17:21

    another solution is catching onClick event and for aggregate data to js function you can

    .hmtl.erb

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

    .js

    // handle my-class click
    $('a.my-class').on('click', function () {
      var link = $(this);
      var array = link.data('array');
    });
    
    0 讨论(0)
提交回复
热议问题