javascript - jQuery 文本到链接脚本?

标签 javascript jquery html anchor

<分区>

有谁知道可以选择所有文本引用 URL 并自动将它们替换为指向这些位置的 anchor 标记的脚本?

For example:

http://www.google.com 

would automatically turn into

<a href="http://www.google.com">http://www.google.com</a>

注意:我想要这个是因为我不想遍历我所有的内容并用 anchor 标签包装它们。

最佳答案

注意:现在可在 https://github.com/maranomynet/linkify 获得此脚本的更新和更正版本。 (GPL/麻省理工学院许可)


嗯...对我来说这似乎是 jQuery 的完美任务。

...我脑子里浮现出这样的事情:

// Define: Linkify plugin
(function($){

  var url1 = /(^|&lt;|\s)(www\..+?\..+?)(\s|&gt;|$)/g,
      url2 = /(^|&lt;|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|&gt;|$)/g,

      linkifyThis = function () {
        var childNodes = this.childNodes,
            i = childNodes.length;
        while(i--)
        {
          var n = childNodes[i];
          if (n.nodeType == 3) {
            var html = $.trim(n.nodeValue);
            if (html)
            {
              html = html.replace(/&/g, '&amp;')
                         .replace(/</g, '&lt;')
                         .replace(/>/g, '&gt;')
                         .replace(url1, '$1<a href="http://$2">$2</a>$3')
                         .replace(url2, '$1<a href="$2">$2</a>$5');
              $(n).after(html).remove();
            }
          }
          else if (n.nodeType == 1  &&  !/^(a|button|textarea)$/i.test(n.tagName)) {
            linkifyThis.call(n);
          }
        }
      };

  $.fn.linkify = function () {
    return this.each(linkifyThis);
  };

})(jQuery);

// Usage example:
jQuery('div.textbody').linkify();

它试图将所有出现的以下内容变成链接:

  • www.example.com/path
  • http://www.example.com/path
  • mailto:me@example.com
  • ftp://www.server.com/path
  • ...以上所有内容都包含在尖括号中(即 < ... > )

享受 :-)

关于javascript - jQuery 文本到链接脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/247479/

相关文章:

javascript - 选择标签中的 onchange 事件!

Javascript:为什么我不能使用 while 循环等待异步任务完成?

javascript - 将base64转换为要在<form>&lt;input name ='file'/>中上传的文件

javascript - 在新的 ajax 加载内容之后刷新 dom 处理程序的最明智的方法是什么?

javascript - 删除具有定义属性的 child - 不起作用

html - 我如何设置 vim 7's html tidy options for "utf-8"编码?

javascript - 在 jquery Accordion 中,如何确保当您单击一个标题时,另一个标题会关闭?

jquery - 横向网站/单行表

asp.net - 如何使 Asp.net Gridview 标题和第一列卡住?

jquery - 用于后拉伸(stretch)的图像的理想尺寸是多少