convert a text link to image link
I am in the middle of making a post system for my website, and i would like some javascript that would turn a text link like
<a href="path/to/image.jpg">Image</a>
into
<a href="pat开发者_开发技巧h/to/image.jpg"><img src="path/to/image.jpg" /></a>
but only turn it into an image link when something such as a regex recognises that the link is to an image.
Or i dont mind doing something like adding a data-type="image" attribute to the link, but i still need the code to turn it into an image link.
I'd recommend putting a class on all of the anchors links you want to convert. Let's say you choose to use a convert
class. Then, you could use jQuery the add an img
tag inside the anchor tag:
// for each anchor that needs converting
$('.convert').each(function() {
// get the href of the anchor
var href = $(this).attr('href');
// create the string we want to append to the anchor
var imgString = '<img src="' + href + '" alt="" />';
// and then append it
$(this).append(imgString);
});
$('a[href$=".png"], a[href$=".jpg"], a[href$=".gif]"').each(function(){
$(this).html('<img src="' + $(this).attr('href') + '" />');
});
Code: http://jsfiddle.net/FcQzG/1/
@Alex solution is a better one, but if you could not add a class
$('a').each(function(){
var a = $(this)
if(a.text() == 'Image')
a.html('<img src="'+a.href+'" >')
})
http://jsfiddle.net/7AvJT/2/
精彩评论