我正在通过 getJSON 提取推文,并使用 javascript 将它们写入 Google map 信息窗口。问题是,这些推文带有文本链接但没有格式(也没有 ids/类/任何可以缩小查找和替换范围的内容)。这是我现在用来查找文本的代码混搭,但我无法将它在 <a>
中找到的内容包装起来。正确显示链接的标签:
function wrap( str ) {
return '<a href="' + str + '">' + str + '<\/a>';
};
function replaceText() {
var jthis = $(this);
$("*").each(function () {
if (jthis.children().length == 0) {
jthis.text(jthis.text().replace(/\bhttp[^ ]+/i, wrap));
}
});
}
$(document).ready(replaceText);
$("html").ajaxStop(replaceText);
我是不是忽略了什么,或者有人知道更好的方法吗?
最佳答案
如果我对您的问题的理解正确,那么这应该可行。 不确定为什么要遍历元素,因为正则表达式无论如何都会扫描所有文本。
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script>
function wrap( str ) {
return '<a href="' + str + '">' + str + '<\/a>';
};
function replaceText() {
$(".tweet").each( function(){
$(this).html($(this).html().replace(/\bhttp[^ ]+/ig, wrap));
})
}
$(document).ready(replaceText);
</script>
</head>
<body>
<div class="tweet"> test 1 http://example.com/path </div>
<div class="tweet"> test 2 http://example.com/path </div>
</body>
</html>
关于javascript - 通过 jquery 查找和替换用 <a> 标签包装文本 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11886566/