Eli*_*nor 40 html javascript anchor jquery
有没有人知道一个脚本可以选择对URL的所有文本引用,并自动用指向这些位置的锚标签替换它们?
For example:
http://www.google.com
would automatically turn into
<a href="http://www.google.com">http://www.google.com</a>
Run Code Online (Sandbox Code Playgroud)
注意:我想要这个,因为我不想浏览我的所有内容并用锚标记包装它们.
Már*_*son 57
注意:此脚本的更新和更正版本现在可从https://github.com/maranomynet/linkify(GPL/MIT许可证)获得
嗯......对我来说,这似乎是jQuery的完美任务.
......这样的事情脱离了我的脑海:
// Define: Linkify plugin
(function($){
var url1 = /(^|<|\s)(www\..+?\..+?)(\s|>|$)/g,
url2 = /(^|<|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|>|$)/g,
linkifyThis = function () {
var childNodes = this.childNodes,
i = childNodes.length;
while(i--)
{
var n = childNodes[i];
if (n.nodeType == 3) {
var html = $.trim(n.nodeValue);
if (html)
{
html = html.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(url1, '$1<a href="http://$2">$2</a>$3')
.replace(url2, '$1<a href="$2">$2</a>$5');
$(n).after(html).remove();
}
}
else if (n.nodeType == 1 && !/^(a|button|textarea)$/i.test(n.tagName)) {
linkifyThis.call(n);
}
}
};
$.fn.linkify = function () {
return this.each(linkifyThis);
};
})(jQuery);
// Usage example:
jQuery('div.textbody').linkify();
Run Code Online (Sandbox Code Playgroud)
它会尝试将以下所有出现的内容转换为链接:
www.example.com/path
http://www.example.com/path
mailto:me@example.com
ftp://www.server.com/path
<
...... >
)请享用 :-)
我有这个功能我打电话
textToLinks: function(text) {
var re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/g;
return text.replace(re, "<a href=\"$1\" title=\"\">$1</a>");
}
Run Code Online (Sandbox Code Playgroud)