I have an a ajax method that hijacks every link in the HTML and preventDefault and then loads the loadPage function().
The method works on all other links that does not have a <img> inside. But when a <a> has a <img> inside the method clickEvent.target.href does not seem to work.
The var url in this instance returns undefined in the console, but on any other links it returns the href.
I’m guessing there is something wrong with I use the target method in this instance?
$('#container a').click(function(clickEvent){
var url = clickEvent.target.href;
if(url.match(urlWebServer)) {
clickEvent.preventDefault();
loadPage(url);
}
});
<div id="user_img">
<a href="somepage.html"><img src="img_user/self.jpg" class="self" /></a>
</div>
Yes, you shouldn’t use the
clickEvent.targetbecause is the target that was clicked. In your case the target isn’t theabut is theimgit contains.Events in fact bubble up, so you click the image and the
clickevent propagates to the top (up to thea) and triggers the event delegate you provided.The solution is to change that line to
Or if you prefer to get the value through jQuery use
The first one is faster.
The solution is that
thisin the handler refers to the DOM element you attach the handler to. Sothiswill refer to thea.