In jQuery, how do i pass an event to a parent anchor if needed?

旧城冷巷雨未停 提交于 2019-12-25 03:53:08

问题


I am in clojurescript using jQuery but the answer should be the same for cljs and js I think.

I have a helper function which creates creates an anchor element then puts an icon element inside of it. My anchor has a unique class for the type of button.

When I do something like

$('.my-btn-type').click(function(e) {console.log(e.target)});

  • prints if icon clicked (even though the handler is on the parent)
  • prints if only anchor is clicked

I constantly have an issue where the icon which is wrapped by the anchor is the event target and not the anchor with the handler attached to it. I am using data attributes in my anchor element which are needed in my handler function. This forces me to manually check if the event.target is the icon or the anchor and then manually bubble up the event or move forward.

This seems hackish and is a pain. There must be a simple way to attach a handler, in jQuery, js, or clojurescript, which would only call the element that the handler is bound to. How do I do this?

edit:

Using "this" was what I needed but in clojurescript the this-as macro is needed. This thread has an exampleenter link description here


回答1:


If I understood it right it seems like you are hooking up the click event for both the anchor and icon.

Or the anchor and the icon have the same class name.

e.g:

<a href="#" class="my-btn-type" >
    <img src="../img/icon.png" class="my-btn-type" />
</a>


来源:https://stackoverflow.com/questions/15530791/in-jquery-how-do-i-pass-an-event-to-a-parent-anchor-if-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!