我希望将网址的文本列表转换为可点击的链接。
<!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
答案 0 :(得分:4)
这是因为您在添加元素之前尝试访问该元素,因此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>