簡體   English   中英

將URL的文本列表轉換為可單擊的HTML鏈接

[英]Convert text list of urls into clickable HTML links

我正在尋找將URL的文本列表轉換為可點擊的鏈接。

<!DOCTYPE html>

<body>  
<script>

// http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/

%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
}

var a1 = document.getElementById("test").innerHTML;
var a2 = replaceURLWithHTMLLinks(a1);
document.getElementById("test").innerHTML = a2;

</script>

<div id="test">
http://www.site.com/
http://www.site2.com/
http://www.site3.com/
</div>

</body>
</html>

Firebug返回控制台中的站點列表:

document.getElementById("test").innerHTML;

即:
www.site.com/
www.site2.com/
www.site3.com/

為什么我在下面的行中出現此錯誤?

var a1 = document.getElementById("test").innerHTML;

TypeError:document.getElementById(...)為null

這是因為您在添加元素之前嘗試訪問該元素,因此document.getElementById('test')返回null。 您可以將它包裝在window.onload下,或者在html元素之后添加腳本。

嘗試:

<script>

// http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/

%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
}

window.onload = function(){
  var elm =  document.getElementById("test");
  var modifiedHtml = replaceURLWithHTMLLinks(elm.innerHTML);
  elm.innerHTML = modifiedHtml ;
}

</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM