I'm trying to read all links on the page and check if link extension is ending with '.png'. If it does, then when that link is clicked, I want to grab that image and append into div with the class 'test'. If link doesn't end with '.png' just ignore it and open normally.
This is markup, you can grab it on jsFiddle too:
<a href="image01.png">Image 01</a>
<a href="image02.png">Image 02</a>
<a href="http://www.google.com/">Page</a>
<a href="image03.png">Image 03</a>
<div class="test"></div>
... and this is how markup should look like when first link is click开发者_高级运维ed:
<a href="image01.png">Image 01</a>
<a href="image02.png">Image 02</a>
<a href="http://www.google.com/">Page</a>
<a href="image03.png">Image 03</a>
<div class="test">
<img src="image01.png" />
</div>
Thanks!
Here is a complete and quite elegant (imho) combination of the posted examples, errors and other stuff fixed
$('a[href$=".png"]').click(function(e) { // nice one ChristopheCVB
$('.test').append($("<img>", {src: this.href})); // neater than "<img src='"+...+">"
e.preventDefault(); // should be enough
});
Demo here
Next we need a test to see if image is already there...
Try this
$("a[href$='.png']").click(function(e){
e.preventDefault();
$(".test").append("<img src='"+this.href+"' />");
});
精彩评论