从haml link_to调用javascript函数

San*_*ung 12 javascript haml onclick link-to

当onclick甚至从haml中的link_to标签触发时,我想调用一个javascript函数(没有JQuery).我怎样才能做到这一点?

edo*_*ere 20

以下是使用haml中的Rails link_to的方法:

= link_to "my link", "", :onclick => "my_function(); return false"
Run Code Online (Sandbox Code Playgroud)


Eli*_*gem 12

我认为这可行:

link_to "your link", href, :onclick => "jsFunction"
Run Code Online (Sandbox Code Playgroud)

或者,做JS方面的一切:

document.body.addEventListener('click',function(e)
{
    var target = e.target || e.srcElement;
    if (target.tagName.toLowerCase() !== 'a')
    {
        return e;//not clicked on link
    }
    //a link was clicked, maybe check class or id or other stuff to narrow it down
    //if a link you were interested in was clicked:
    return theClickFunction.apply(target,[e]);
},false);
Run Code Online (Sandbox Code Playgroud)


Fel*_*vni 7

纯粹的HAML相当于@ edouardbriere的答案:

%a{href: '#', onclick: 'my_function(); return false;'} my link
Run Code Online (Sandbox Code Playgroud)