使@username可点击jquery
问题描述:
下面的代码适用于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>';
}));
答
试试这个:
$('#test').html($('#test').html().replace(/\B\@([\w\-]+)/gim, function(match, name){
return '<a href="http://twitter.com/users/' + name + '">' + match + '</a>';
}));
答
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 ,而不是get
和set
答
一个用于微博的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/
这也与转换哈希代码和网址
应该帮助需要注意的是选择将元素类型工作,除非用'#'(对于ID)或'前面加上交易。 '(为班级)。 – bdares 2012-02-28 13:44:49
工作,谢谢。 – Cindro 2012-02-28 16:29:14
对不起,罗瑞,我庆祝得太早。我看看这个,它只是重复第一段而不是全部。 http://jsfiddle.net/hnAQX/ – Cindro 2012-02-28 22:07:19