2011-05-04 32 views
1

我使用“Linkify”添加链接到静态文本...这是我使用的是什么:添加<wbr>和省略号长链接(与jquery.linkify linkified)

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

我想在15个字符后添加一个<wbr>(分词符),在30个左右后分配一个&hellip; ...(如果链接是< 30个字符,请不要加上......)

因此,链接会是这样的:https://github.com/mara<wbr></wbr>nomynet/linkify&hellip;

我想我必须在var jquery.linkify-1.0.js中使用变量“$ 2”,但我对如何做到这一点感到困惑...

任何线索?

谢谢!

回答

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 = '&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` 
    }, 

我测试过的代码块的一些变化,他们似乎都工作,所以让我知道,如果你碰上那并不是一个例子工作。

+0

哇!这很简单!我非常感谢你的帮助!非常感谢Brad! – Santiago 2011-05-07 05:51:21