I am running an ajax function that calls an external page but am having trouble selecting an anchor tag that has an image inside of it. The function works when it is plain text but once there is an image inside it ceases to function (except when clicked outside of the image but within the anchor tag).
The html is something like this.
<div id="add_content">
<a href="page_1.html"> Text works fine</a>
<a href="page_2.html"><img src="thumbnail.jpg"/>Image doesn't work</a>
</div>
<div id="insert_here"> </div>
An example external page is
<div id="thumbnails">
<img src="images/1.jpg"/>
<img src="images/2.jpg"/>
<img src="images/3.jpg"/>
</div>
The script that I am running is
$(document).ready(function (){
$('#add_content a').click(function(e){
e.preventDefault();
$('#insert_here').load(e.target.href + '#thumbnails').hide().delay(100).fadeIn(500);
});
});
Change
e.target.hreftothis.href:If you click on the child image then
e.targetwill be that image, and the image doesn’t have anhrefproperty. The click event is bound to the anchors, so within the click handlerthiswill be the anchor that was clicked.The reason your current code worked “when clicked outside of the image but within the anchor tag” is because in that case
e.targetis the anchor itself.