Rails: using link_to to make a link without href

后端 未结 8 1802
情书的邮戳
情书的邮戳 2020-12-29 19:05

How can I use the link_to helper to make a link without an href attribute? I want to make a link exclusively for a javascript action, I don\'t want

相关标签:
8条回答
  • 2020-12-29 19:25

    I use this approach:

    = link_to('Click me', 'javascript:;', :id => :foo)
    

    Its basically a Javascript no-op

    0 讨论(0)
  • 2020-12-29 19:25

    An example for rails 5 would be:

    <%= content_tag("a", image_tag("/logo.png"), class: "navbar-brand") %>

    This would render as:

    <a class="navbar-brand"><img src="/logo.png" alt="Logo"></a>

    This is similar to niels' answer but with a nested image_tag and a class.

    Source: Rails API

    0 讨论(0)
  • 2020-12-29 19:25

    I prefer using plain HTML without href attribute at all in such cases:

    <a data-toggle="modal" data-target="#myModal">Open dialog</a>
    

    IMHO it is more readable than content_tag("a","link text").

    • The disadvantage of href=# is that the browser will scroll to the top when clicked by default
    • javascript:; looks ugly
    0 讨论(0)
  • 2020-12-29 19:32

    I think you're better off using a button in situations where there is no href.

    <button class='button'>Hello</button>
    
    0 讨论(0)
  • 2020-12-29 19:33

    You can also use a

    content_tag("a","link text")
    

    which gives you

    <a>link text</a>
    

    See: rails api

    0 讨论(0)
  • 2020-12-29 19:34

    An alternative is

    = link_to("My hyperlink", "#")
    

    This will give you a link that when clicked, does not reload the page like passing in nil. At the same time, it will set the mouse to pointer on mouseover, which you will not get with the content_tag approach.

    0 讨论(0)
提交回复
热议问题