将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;
类型错误:document.getElementById(…)为空
这是因为您试图在添加元素之前访问该元素,所以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>
相关文章:
- ReactJS映射:如何仅在url变量不为空时呈现html链接
- 如何使用JavaScript访问HTML链接内容
- 从HTML链接时,Javascript文件不起作用
- html链接onclick弹出一个表单
- 将点击函数添加到动态 HTML 链接
- 如何在 html 链接中发送参数以及如何检索它
- HTML 链接变量
- 如何使html链接标签可以在没有标签的情况下工作
- 提交表单的可能性(左-/中-/在新选项卡或窗口中打开-)单击html链接
- 使用本地HTML链接打开Windows文件夹
- 如何将JavaScript数组输出到HTML链接
- 指向leanModal.js的链接在通过HTML链接呈现时工作良好,但在React中则不然
- 在visualforce中为更新字段分配HTML链接/按钮
- 将URL的文本列表转换为可点击的HTML链接
- 按日期为iframe创建一个HTML链接
- 如何在页面刷新时保持选定/活动的HTML链接颜色
- 如何通过html链接将特定对象传递给函数
- Html链接在某些单击时未注册
- 我想让HTML链接打开一个js手风琴
- 如何在谷歌网站中显示与iframe中的特定人员共享的谷歌云端硬盘html链接