2012-02-28 68 views
0

下面的代碼適用於Mootools庫,如果可能的話,我希望它可以在jQuery上工作,但我至今沒有運氣。使@username可點擊jquery

HTML

<p id="test">@user has an email address of [email protected] See! the regexp works @people!</p> 

MooTools的

$('test').set('html', $('test').get('html').replace(/\B\@([\w\-]+)/gim, function(match, name){ 
    return '<a href="http://twitter.com/users/' + name + '">' + match + '</a>'; 
})); 

Fiddle

回答

3

試試這個:

$('#test').html($('#test').html().replace(/\B\@([\w\-]+)/gim, function(match, name){ 
    return '<a href="http://twitter.com/users/' + name + '">' + match + '</a>'; 
})); 

Example fiddle

+0

應該幫助需要注意的是選擇將元素類型工作,除非用'#'(對於ID)或'前面加上交易。 '(爲班級)。 – bdares 2012-02-28 13:44:49

+0

工作,謝謝。 – Cindro 2012-02-28 16:29:14

+0

對不起,羅瑞,我慶祝得太早。我看看這個,它只是重複第一段而不是全部。 http://jsfiddle.net/hnAQX/ – Cindro 2012-02-28 22:07:19

1

Fiddled與這個有點給你:

$('#test').html($('#test').html().replace(/\B\@([\w\-]+)/gim, function(match, name){ 
    return '<a href="http://twitter.com/users/' + name + '">' + match + '</a>'; 
}));​ 

關鍵的區別是:

  • 使用element.html()的方法來獲取和設置HTML前綴來#
  • 選擇找到test按id ,而不是getset
0

一個用於微博的mootools原生解決方案 - 我知道你想要去jquery路線但僅供參考。

String.implement({ 
    linkify: function(){ 
     // courtesy of Jeremy Parrish (rrish.org) 
     return String(this).replace(/(https?:\/\/[\w\-:;?&=+.%#\/]+)/gi, '<a href="$1">$1</a>') 
      .replace(/(^|\W)@(\w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>') 
      .replace(/(^|\W)#(\w+)/g, '$1#<a href="http://search.twitter.com/search?q=%23$2">$2</a>'); 
    } 
}); 


var tests = [ 
    "@user has an email address of [email protected] See! the regexp works @people!", 
    "@d_mitar likes #mootools a fair bit. http://foo.com#bar" 
]; 



// on proto 
tests.each(function(el) { 
    new Element("div", { 
     html: el.linkify() 
    }).inject(document.body); 

}); 

// on host object 
tests.each(function(el) { 
    new Element("div", { 
     html: String.linkify(el) 
    }).inject(document.body); 

}); 

http://jsfiddle.net/dimitar/fG4KF/

這也與轉換哈希代碼和網址