开发者

Make a hyper link on Html link with Jquery

开发者 https://www.devze.com 2023-02-04 14:41 出处:网络
I have Html contents like <span> http://j.mp/eUcRNK </span> I want to hyperlink on above html text like this

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' />")
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号