当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Replace text by html. Jquery

问题描述:

I'm trying to replace text by html tags. I'm using this code:

 $('p').each(function () {

$(this).text($(this).text().replace(/(http:\/\/.+?)(\s|$)/g, function(text, link) {

return '<a href="'+ link +'" target="blank">'+ link +'</a>';

}).replace(/(www\..+?)(\s|$)/g, function(text, link) {

return '<a href="http://'+ link +'" target="blank">'+ link +'</a>';

})

);

});

But the problem is that it's not replacing the text by html, but by another text.

For example:

 www.google.com

becomes (still in text):

 <a href="http://www.google.fr" target="blank">www.google.fr</a>

Any idea on how I could solve that?

网友答案:
$(this).text(...)

You're setting the text of the element.

To set HTML, call .html().

网友答案:

use .html() :

 $('p').each(function () {
    $(this).html($(this).text().replace(/(http:\/\/.+?)(\s|$)/g, function(text, link) {
               return '<a href="'+ link +'" target="blank">'+ link +'</a>';
            }).replace(/(www\..+?)(\s|$)/g, function(text, link) {
               return '<a href="http://'+ link +'" target="blank">'+ link +'</a>';
                })
            );  
        });

Working Demo

分享给朋友:
您可能感兴趣的文章:
随机阅读: