代码之家  ›  专栏  ›  技术社区  ›  4imble

使用JQuery创建段落中的超链接

  •  1
  • 4imble  · 技术社区  · 16 年前

    如何使用JQuery在某些文本中查找url并将其自动转换为实际的超链接?

    示例文本,

    var TextMemo=“这是一些随机事件 网站在这里。www.stackoverflow.com 这次又来了一个 http://www.google.co.uk )"

    这是一项简单的任务吗?

    非常感谢, 科汉

    3 回复  |  直到 16 年前
        2
  •  0
  •   James    16 年前

    首先,它不会像替换单个字符串中的文本那样简单,因为一个典型的段落将由一个或多个文本和元素节点组成,这些节点需要正确地遍历,以便有效地包装所需的文本片段。您不应该使用innerText/textContent或innerHTML之类的内容获取文本。

    试试这个:

    var para = jQuery('#my-para')[0];
    
    findMatchAndReplace(
        para,
        /\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]/i,
        '<a href="$&">$&</a>'
    );
    

    function findMatchAndReplace(node, regex, replacement) {
    
        var parent,
            temp = document.createElement('div'),
            next;
    
        if (node.nodeType === 3) {
    
            parent = node.parentNode;
    
            temp.innerHTML = node.data.replace(regex, replacement);
    
            while (temp.firstChild)
                parent.insertBefore(temp.firstChild, node);
    
            parent.removeChild(node);
    
        } else if (node.nodeType === 1) {
    
            if (node = node.firstChild) do {
                next = node.nextSibling;
                findMatchAndReplace(node, regex, replacement);
            } while (node = next);
    
        }
    
    }
    
        3
  •  0
  •   Community Mohan Dere    9 年前