本文介绍了使用jQuery在HTML链接上建立超级链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似HTML的内容

I have Html contents like

<span>
 http://j.mp/eUcRNK
</span>

我想在上面的html文本上超链接

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>

我该怎么做..

推荐答案

$('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>");
}

更新了小提琴

对于jquery 1.3.2,只需稍微更改一下jQuery代码即可.

updated fiddle

for jquery 1.3.2, just change the jQuery codes a bit.

var span = $('span');
span.html(replaceURLWithHTMLLinks(span.html()));

这篇关于使用jQuery在HTML链接上建立超级链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 08:47