简体   繁体   English

从haml link_to调用javascript函数

[英]call javascript function from haml link_to

I would like to invoke a javascript function (without JQuery) when the onclick even fires from a link_to tag in haml. 当onclick甚至从haml中的link_to标签触发时,我想调用一个javascript函数(没有JQuery)。 How can I do this? 我怎样才能做到这一点?

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

= link_to "my link", "", :onclick => "my_function(); return false"

I think this could work: 我认为这可行:

link_to "your link", href, :onclick => "jsFunction"

Or, doing everything JS side: 或者,做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);

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

%a{href: '#', onclick: 'my_function(); return false;'} my link
<a onclick="YOURMETHOD;"/>A link</a>

如果您还想阻止位置更改,请在方法调用后添加return false

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

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