我正在使用“Linkify”添加静态文本链接......这就是我正在使用的内容:
https://github.com/maranomynet/linkify/blob/master/1.0/jquery.linkify-1.0.js
我想在15个字符后添加<wbr>
(分词),在30左右后添加…
...(如果链接是&lt; 30个字符,请勿添加......)
因此,链接类似于:https://github.com/mara<wbr></wbr>nomynet/linkify…
我想我必须使用jquery.linkify-1.0.js中的var“$ 2”,但我对如何做到这一点感到有点困惑......
有任何线索吗?
谢谢!
答案 0 :(得分:3)
我不假装是一个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步:更改linkify功能。替换这个:
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`
},
我已经测试了一些代码块的变体,它们看起来都有效,所以如果你碰到一个不起作用的例子,请告诉我。