繁体   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