我有一个Backbone App,我通过API获取Twitter推文,该结果以字符串形式返回结果。我需要的是使字符串中的http可点击。我怎样才能做到这一点?
这是文本字符串:
Who does John wish he could have sung with over the span of his career? See the video answer here! http://t.co/pbPXaDkGEJ
我希望它像
<span>Who does John wish he could have sung with over the span of his career? See the video answer here! <a href="http://t.co/pbPXaDkGEJ"> click here</a></span>
我尝试过这样的事情:
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
但那不起作用......
[UPDATE]
好的,我要添加我的Backbone View:
function (App, Backbone) {
var ArtistTwitter = App.module();
ArtistTwitter.View = Backbone.View.extend({
tagName: 'ul',
className: 'actweets',
template: 'artistTwitter',
initialize: function() {
this.listenTo(this.collection, 'all', this.render);
},
serialize: function() {
return this.collection ? this.collection.toJSON() : [];
}
});
ArtistTwitter.ArtistTwitterCollection = Backbone.Collection.extend({
url: function() {
return '/myproject/index.php/api/social_feeds/fetchNewTweet/' + this.artist_id;
}
});
return ArtistTwitter;
}
我尝试在afterRender
- 函数中添加上面提到的替换代码但是没有用...
欢迎任何建议......
答案 0 :(得分:0)
它正确地替换了链接,但您需要稍微修改它以获得预期的输出。如果我理解正确,您只需将sencond $ 1更改为静态文本'click here'即可获得所需的输出:
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>click here</a>");
}
这将返回:
replaceURLWithHTMLLinks("Who does John wish he could have sung with over the span of his career? See the video answer here! http://t.co/pbPXaDkGEJ ")
"Who does John wish he could have sung with over the span of his career? See the video answer here! <a href='http://t.co/pbPXaDkGEJ'>click here</a> "
更新:
在这种情况下,我认为你应该能够通过在你的模型视图中添加repleaceURLWithHTMLLinks来获得你想要的东西(你粘贴的视图是你的集合)并实现渲染方法:
ArtistTwitterItemView.View = Backbone.View.extend({
tagName: 'li',
replaceURLWithHTMLLinks: function(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>click here</a>");
},
// something like this (copy paste will not work but it might get you on the track):
// it looks like this should in be a model view
// in collections view you should iterate through your collection and call render for each item
// in the case for model view call replaceURLWithHTMLLinks before rendering:
render: function(){
var data = this.model.toJSON();
_.extend(data, { replacedText: replaceURLWithHTMLLinks(data.text) });
var html = _.template($(this.template), data);
this.$el.html(html);
}
});