使用jQuery或Javascript将段落中的URL转换为链接

使用jQuery或Javascript将段落中的URL转换为链接,javascript,jquery,html,Javascript,Jquery,Html,我不熟悉javascript,但了解jQuery。我正试图使用这段代码将www.和http in p标记转换为工作链接 这是我正在使用的代码,问题是我不完全理解代码是如何工作的,有人能解释一下吗 <script> var re = /(http:\/\/[^ ]+)/g; function createLinks(els) { $(els).contents().each(function () { if (this.nodeType === 1 &

我不熟悉javascript,但了解jQuery。我正试图使用这段代码将www.和http in p标记转换为工作链接

这是我正在使用的代码,问题是我不完全理解代码是如何工作的,有人能解释一下吗

<script>
var re = /(http:\/\/[^ ]+)/g;

function createLinks(els) {
    $(els).contents().each(function () {
        if (this.nodeType === 1 && this.nodeName !== 'script') {
            createLinks(this);
        } else if (this.nodeType === 3 && this.data.match(re)) {
            var markup = this.data.replace(re, '<a href="$1">$1</a>');
            $(this).replaceWith(markup);
        }
    });
}

createLinks(document.body);
</script>

var re=/(http:\/\/[^]+)/g;
函数createLinks(els){
$(els).contents().each(函数(){
if(this.nodeType==1&&this.nodeName!==script){
createLinks(这个);
}else if(this.nodeType==3&&this.data.match(re)){
var markup=this.data.replace(re');
$(此).replacetwith(标记);
}
});
}
createLinks(document.body);

首先,为匹配文本设置正则表达式模板,该模板从“http://”

第二,创建遍历整个html文档的递归函数

nodeType==1表示当前元素是html标记(即a、p、div等)

nodeType==2表示元素是属性

nodeType==3表示元素是文本节点

所以当你找到html标签时,你在里面搜索, 当您找到文本节点时,您正在通过正则表达式进行检查,如果此文本从“http://”开始,如果是,则将此文本更改并回复到

最后你调用你的函数,从body开始作为一个根

//create a regular expression to format the link 
var re = /(http:\/\/[^ ]+)/g;

//this is the create links function which gets called below, "els" is the elements passed to the function (document.body)
function createLinks(els) {

    //for each of the elements in the body
    $(els).contents().each(function () {

        //check if its an element type but not a script
        if (this.nodeType === 1 && this.nodeName !== 'script') {

            //call the create links function and send in this object
            createLinks(this);

        //if its not an element but is a text node and the format matches the regular expression
        } else if (this.nodeType === 3 && this.data.match(re)) {

            //create the markup
            var markup = this.data.replace(re, '<a href="$1">$1</a>');

            //finally, replace this link with the marked up link
            $(this).replaceWith(markup);
        }
    });
}
//call the create links function
createLinks(document.body);
//创建正则表达式以格式化链接
var re=/(http:\/\/[^]+)/g;
//这是下面调用的createlinks函数,“els”是传递给函数(document.body)的元素
函数createLinks(els){
//对于主体中的每个元素
$(els).contents().each(函数(){
//检查它是否是元素类型而不是脚本
if(this.nodeType==1&&this.nodeName!==script){
//调用createlinks函数并发送此对象
createLinks(这个);
//如果不是元素而是文本节点,且格式与正则表达式匹配
}else if(this.nodeType==3&&this.data.match(re)){
//创建标记
var markup=this.data.replace(re');
//最后,用标记的链接替换此链接
$(此).replacetwith(标记);
}
});
}
//调用createlinks函数
createLinks(document.body);

我希望注释的代码有助于您理解。

这个问题似乎离题了,因为它是关于解释现有代码的,应该在“要么”或“谢谢您的帮助”上。我真的很感谢您的帮助。谢谢您,帮助了很多人!