javascript - 将所有文本链接转换为实际链接

标签 javascript jquery html

如何将页面中的所有文本链接转换为实际链接?

例如,我想像这样更改所有文本链接:

<p>http://www.google.com</p>

或者在这样的表格中:

<td>http://www.google.com</td>

进入这个:

<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\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/);
      }).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>

关于javascript - 将所有文本链接转换为实际链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15736403/

相关文章:

javascript - 如何在不退出 javascript 的情况下从 javascript 更新网页

javascript - 编辑列表中每个 div 的样式属性

javascript - 单击按钮时的 Facebook 点赞框事件

javascript - 如何等待浏览器在卸载时发送图像请求?

html - 如何创建一个只接受 2 个字符的文本框

html - 在网站上导航时Musicplayer停止

带有预编译脚本的 Javascript 模板引擎?

javascript - 如何重新加载html标签对象数据?

javascript - 如何让一个<div>上的 'setTimeout'自动转到另一个<div>?

javascript - div 上的 keyup for backspace 不提醒键码