Javascript 将所有文本链接转换为实际链接
如何将页面中的所有文本链接转换为实际链接 例如,我想更改所有文本链接,如下所示:Javascript 将所有文本链接转换为实际链接,javascript,jquery,html,Javascript,Jquery,Html,如何将页面中的所有文本链接转换为实际链接 例如,我想更改所有文本链接,如下所示: <p>http://www.google.com</p> <td>http://www.google.com</td> http://www.google.com 或者在这样的表格中: <p>http://www.google.com</p> <td>http://www.google.com</td> htt
<p>http://www.google.com</p>
<td>http://www.google.com</td>
http://www.google.com
或者在这样的表格中:
<p>http://www.google.com</p>
<td>http://www.google.com</td>
http://www.google.com
为此:
<a href="http://www.google.com">http://www.google.com</a>
这是:
<td><a href="http://www.google.com">http://www.google.com</a></td>
我想这个问题以前有人问过 答案如下: 这就是您需要的:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function createLinks(){
$('p, td').filter(function() {
return this.innerHTML.match(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/);
}).each(function(){
var link = $('<a>', { href: this.innerHTML,
text: this.innerHTML });
if(this.tagName == "P")
this.parentNode.replaceChild(link[0], this);
else{
this.removeChild(this.childNodes[0])
this.appendChild(link[0]);
}
});
}
$(document).ready(function(){
$('#create_links').click(function(){
createLinks();
});
});
</script>
<style>
a{
display:block;
}
</style>
</head>
<body>
<p>This shouldn't became a link</p>
<p>http://www.thisshouldbecamealink.com</p>
<p>http://www.anotherlink.com</p>
<table>
<tr>
<td>Not a link</td>
</tr>
<tr>
<td>http://www.validlink.com</td>
</tr>
</table>
<button id="create_links">Create links</button>
</body>
</html>
函数createLinks(){
$('p,td').filter(函数(){
返回此.innerHTML.match(/(http | ftp | https):\/\/[\w\-\+(\.[\w\-\+)+([\w\-\,@?^=%&;:/~\+\\\\\\\\\\]*[\w\-\\\\\\\\\\\\\\\\\\\++])/;
}).each(函数({
var link=$('',{href:this.innerHTML,
text:this.innerHTML});
如果(this.tagName==“P”)
this.parentNode.replaceChild(链接[0],this);
否则{
this.removeChild(this.childNodes[0])
这个.appendChild(链接[0]);
}
});
}
$(文档).ready(函数(){
$(“#创建链接”)。单击(函数(){
createLinks();
});
});
a{
显示:块;
}
这不应该成为一种联系
http://www.thisshouldbecamealink.com
http://www.anotherlink.com
没有链接
http://www.validlink.com
创建链接
为什么页面上的地址不是超链接?@leetylor,你以前从未见过这种情况?例如,如果有人粘贴了一个超链接,而你想自动链接它,那么博客页面又如何呢。我认为这是一个非常好的问题,不值得投反对票。@Jessemon是的,当然。“我想试着获取更多的信息,了解OP对其页面内容的控制程度。”李泰勒。好的,很酷。如果可能的话,我认为在服务器端制作超链接是个好主意D@Jessemon-没错,这正是我想要暗示的。。。