添加& lt; wbr>和省略号的长链接(链接与jquery.linkify)



我使用"Linkify"添加链接到静态文本…这就是我使用的:

https://github.com/maranomynet/linkify/blob/master/1.0/jquery.linkify-1.0.js

我想在15个字符之后添加一个<wbr>(断行),在30个字符之后添加一个&hellip;…(如果链接是<30个字符,不要添加& help;)

那么,链接应该是这样的:https://github.com/mara<wbr></wbr>nomynet/linkify&hellip;

我想我必须在jquery.link -1.0.js中使用var"$2",但我对如何做到这一点有点困惑…

什么线索吗?

谢谢!

我不假装是一个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 = '&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`
  },

我已经测试了一些代码块的变化,它们似乎都可以工作,所以如果你遇到一个不工作的例子,请告诉我。

最新更新