简体   繁体   English

Link_to Image_tag onclick 失火(Rails + JS)

[英]Link_to Image_tag onclick misfiring (Rails + JS)

I noticed this weird behavior when I do the following:当我执行以下操作时,我注意到了这种奇怪的行为:

 <%= link_to(image_tag('some_image', class:"some_class", onclick:"someFunction(event)"),some_path) %>

later calling event.target;稍后调用event.target; returns undefined .返回undefined I investigated this and it is because the event is the image_tag instead of the link_to .我对此进行了调查,这是因为eventimage_tag而不是link_to

so I guess my question is: why does this happen and how do I prevent it?所以我想我的问题是:为什么会发生这种情况,我该如何预防?

I ended up splitting the link and the image and putting the onclick on the link_to (the image is obviously not clickable and there's this ugly button under it, just curious if there is a way around this.我最终将链接和图像分开,并将onclick放在link_to上(图像显然不可点击,下面有一个丑陋的按钮,只是好奇是否有办法解决这个问题。

Thanks in advance!提前致谢!

Events traverse up the dom tree, aka bubble up.事件遍历 dom 树,也就是冒泡。 target returns the element where the click happened. target返回点击发生的元素。 currentTarget returns the element where handler function is attached. currentTarget返回附加了处理程序 function 的元素。

<a onclick="clickable(event)" href="#">
  <img src="/assets/sample.jpg">        <!-- if you click `img` -->
</a>

<script type="text/javascript">
  function clickable(event){
    console.log(event.target)           <!-- this will return `img` -->
    console.log(event.currentTarget)    <!-- this will return `a` -->
  }
</script>
<a onclick="clickable(event)" href="#"> <!-- if you click `a` -->
  <img src="/assets/sample.jpg">     
</a>

<script type="text/javascript">
  function clickable(event){
    console.log(event.target)           <!-- this will return `a` -->
    console.log(event.currentTarget)    <!-- this will return `a` -->
  }
</script>

If you need to get the link, make sure onclick is on the link and then call currentTarget .如果您需要获取链接,请确保onclick在链接上,然后调用currentTarget

This will add link to image and event.target will be image.这将添加指向图像的链接,并且event.target将是图像。

<%= link_to image_tag('some_image', class:"some_class"), some_path, onclick: "someFunction(event)" %>

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

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