我不假装自己是 JavaScript/jQuery 大师,但这就是我想出的似乎可行的方法。如果有人有更好的方法来执行某些功能,我会全力以赴——我更像是一个 C# 人,所以 Javascript/jQuery 是我正在努力改进的一个薄弱环节。
第 1 步:将这段代码放在 linkify 插件可以读取的地方(我把它放在了 linkify 文件中)。
function FormatLink(a) {
// Configurable settings
var wbrPosition = 15;
var hellipPosition = 30;
var wbr = '<wbr></wbr>';
var hellip = '…';
// Put the data into a span, makes it so we can alter it without losing surrounding text.
var link = $('<span>' + a + '</span>');
// If no href, this is not a URL. Pass it back.
if (link.find('a').attr('href') == undefined) {
return a;
}
jQuery.each(link.find('a'), function () {
var original = $(this).html() + '</a>';
var updated = $(this);
// Set length
var length = updated.html().length;
if (length > hellipPosition) {
updated.html(updated.html().substr(0, hellipPosition) + hellip);
}
if (length > wbrPosition) {
updated.html(updated.html().substr(0, wbrPosition) + wbr + updated.html().substr(wbrPosition, length));
}
if (link.html() !== null && link.find('a').html() !== null && original !== null && updated.html() !== null) {
var changes = link.html().replace(original, updated.html() + '</a>');
if (changes !== null && changes !== '') {
link.html(changes);
}
}
});
return link.html();
}
步骤 2:更改链接功能。替换这个:
linkifier = function ( html ) {
return html
.replace( noProtocolUrl, '$1<a href="<``>://$2">$2</a>$3' ) // NOTE: we escape `"http` as `"<``>` to make sure `httpOrMailtoUrl` below doesn't find it as a false-positive
.replace( httpOrMailtoUrl, '$1<a href="$2">$2</a>$3' )
.replace( /"<``>/g, '"http' ); // reinsert `"http`
},
有了这个:
linkifier = function (html) {
return FormatLink(html
.replace(noProtocolUrl, '$1<a href="<``>://$2">$2</a>$3') // NOTE: we escape `"http` as `"<``>` to make sure `httpOrMailtoUrl` below doesn't find it as a false-positive
.replace(httpOrMailtoUrl, '$1<a href="$2">$2</a>$3')
.replace(/"<``>/g, '"http')); // reinsert `"http`
},
我已经测试了一些代码块的变体,它们似乎都可以工作,所以如果你遇到了一个不起作用的例子,请告诉我。