2011-01-11 16 views
0

HTML鏈接一個超鏈接我的HTML內容一樣就用jQuery

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

我希望在超鏈接上面這樣

<span> 
    <a href="http://j.mp/eUcRNK" class="link" target="_blank"> 
    http://j.mp/eUcRNK 
    </a> 
</span> 

我如何能做到這一點的HTML文本..

回答

2
$('span').html(function(i,txt){ 
    return $('<a>').text(txt).attr({'target':'_blank', 'href': txt }).addClass('link'); 
}); 

demo

根據下面的評論,我想這解決了它。

$('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

的jQuery 1.3.2,只是改變了jQuery代碼一點。

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

another updated fiddle