Make a hyper link on Html link with Jquery
I have Html contents like
<span>
http://j.mp/eUcRNK
</span>
I want to hyperlink on above html text like this
<span>
<a开发者_如何学编程 href="http://j.mp/eUcRNK" class="link" target="_blank">
http://j.mp/eUcRNK
</a>
</span>
How I can do that..
$('span').html(function(i,txt){
return $('<a>').text(txt).attr({'target':'_blank', 'href': txt }).addClass('link');
});
demo
based on the comments below, I guess this solves it.
$('span').html(function(i,txt){
return replaceURLWithHTMLLinks(txt);
});
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp,"<a class='link' href='$1' target='_blank' >$1</a>");
}
updated fiddle
for jquery 1.3.2, just change the jQuery codes a bit.
var span = $('span');
span.html(replaceURLWithHTMLLinks(span.html()));
another updated fiddle
Try
$("span").each(function(){
var text = $(this).text();
$(this).contents().wrap("<a class='link' href='" + text + "' target='_blank' />")
});
精彩评论