【问题标题】:Transform all text links into actual links将所有文本链接转换为实际链接
【发布时间】:2013-04-01 01:14:10
【问题描述】:

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

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

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

【问题讨论】:

  • 为什么页面的地址不是超链接?
  • @LeeTaylor,你从来没见过这个?例如,有人粘贴超链接并且您想自动链接它的博客页面怎么样。我认为这是一个非常好的问题,不值得投反对票。
  • @Jessemon 是的,当然。我要求尝试获取更多信息,了解 OP 对其页面内容的控制程度。
  • @LeeTaylor。好的酷。我认为如果可能的话,在服务器端制作超链接是个好主意。 :D
  • @Jessemon - 没错,这就是我想要暗示的......

标签: javascript jquery html


【解决方案1】:

这是你需要的:

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

【讨论】:

    【解决方案2】:

    我想这个问题以前有人问过。

    答案如下:

    jQuery Text to Link Script?

    【讨论】:

      猜你喜欢
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 2014-02-22
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多