Click event on button is sending an icon as the target?

前端 未结 5 1465
走了就别回头了
走了就别回头了 2020-12-24 07:17

I am having an issue very similar to: \"Jquery \'click\' not firing when icon is on button\" however the resolution for that post is not providing a solution for me, so I th

5条回答
  •  爱一瞬间的悲伤
    2020-12-24 07:51

    It's caused by event propagation. You click on the icon, which is inside the button, so the click event propagates up through the DOM from the icon, to the button, all the way up to the document. This results in your click event handler code being executed.

    If the issue is that you just want the reference to the button every time that code runs, but you still want it to trigger when you click on the icon instead of the text, you just need to use this rather than event.target:

    var $btn = $(this);
    ...
    

    jQuery will make sure that this always refers to the button, even if the actual event.target element is an element inside it.

提交回复
热议问题