首页 > 解决方案 > 来自文本的打开链接变成可点击的链接

问题描述

我正在尝试使用 jQuery 自动打开一个链接(最初是纯文本)。

在 html 代码中,链接是这样编写的:

<p><strong>Page URL:</strong><br />
https://www.google.com/</p> 

我使用此代码将文本转换为可点击的链接:

(function($) {
    $(document).ready(function() {
        $('p').eq(7).html($('p').eq(7).html().replace(/(https?:\/\/.+?)(?:\s|$)/ig, '<a href="$1">$1</a> '));

    });

})(jQuery);

我试图调整一些我在已经可点击的链接上成功使用的其他代码,但我就是想不通:

this.$ = this.jQuery = jQuery.noConflict(true);
var baseUrl = "http://www.google.com/";
var matchingLinks = $( "a[href*='" + baseUrl + "']" );
$(matchingLinks).each(
    function(index)
    {
        window.open( $(this).attr( "href" ) );
    }
);

谢谢!

标签: jqueryautomationclickable

解决方案


你不需要 JQuery。这段代码可以帮助你。

function htmlchars(string) {return string.replace(/[\x00-\x1f\xff-\uffff]/g,function(v) {return "&#" + v.charCodeAt() + ";"})};
document.documentElement.replace(/https?:\/\/.+?(?:\s|$)/gi,function(v){return "<a href=\"" + htmlchars(v) + "\">" + htmlchars(v) + "</a>"});

我不知道它正在工作。我无法尝试。


推荐阅读