简体   繁体   中英

Jquery listener for clicking a class, but not working when clicking the icon inside it

First of all, I couldn't find this question over here, so I don't know if it has been answered yet.

I have a listener for all the clicks in my site, and then calls a function that checks if the target has the class "wave". If so, it displays a wave effect.

I have tiles with this class, and it works fine, except they have large icons, and if you click them, it does not recognise it as a target with the class.

I tried to put all the tiles inside a div with the class, but somehow it does not recognise it as a target with this class either (I'm assuming it recognize as clicking the target inside them).

I tried to put the 'true' at the end of the listener, in case the bubbling direction could help me, but it didn't.

Any idea? thanks in advance and sorry for my ignorance.

jsfiddle

    <div class="tile-container">
  <div class="tile efecteona">
   <h3 class="titol-tile">Gràfics</h3>
   <i class="fa fa-bar-chart tile-icon "></i>
  </div>
</div>

"efecteona" would be "wave" class https://jsfiddle.net/qtLvef8o/2/

As the other answers note, the target returns the actual clicked element which in this case is the icon and not the div with the class.

Since you use jQuery though, why not use its delegate syntax which allows for this ?

$(document).on('click', '.efecteona, button', addOnaEffect);

and set target = this inside your hander.

updated demo at https://jsfiddle.net/qtLvef8o/4/

When you are asking about the e.target it gets the i element, and the i element doesn't have the class you need and neither had the tagname button.

Add this console.log(target); next to your line var target = e.target; and you will see what I'm saying.

When you click an element the event bubbles all the way up to the document, while the target is always the element which initialized it. In your case, it seems that your code assumes the target is a tile element, while in fact it can also be the icon element.

Since you tagged on the question that you are using jQuery, there's a simple solution. Use jQuery closest method.

var target = $(e.target).closest('.efecteona, button').get(0);

Code example

The target is wrong is this case.

I tried to explain by resetting the target when it's the parent that has the class (a bit dirty, can be optimised / better written but it's just to explicitly show the target issue)

https://jsfiddle.net/OxyDesign/wbxvqt2b/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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