【问题标题】:wrapping a text url with <a> tags via jquery find and replace通过jquery查找和替换用<a>标签包装文本url
【发布时间】:2012-08-06 20:44:54
【问题描述】:

我正在通过 getJSON 提取推文并使用 javascript 将它们写入 Google 地图信息窗口。问题是,这些推文带有文本链接,但没有格式(也没有 ids/classes/任何可以缩小查找和替换的内容)。这是我现在用来查找文本的代码混搭,但我无法将它在&lt;a&gt; 标签中找到的任何内容包装起来以正确显示链接:

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);

我是否忽略了某些事情,或者有人知道更好的方法吗?

【问题讨论】:

标签: javascript jquery regex replace


【解决方案1】:

如果我正确理解您的问题,这应该可以。 不知道为什么要遍历元素,因为正则表达式无论如何都会扫描所有文本。

<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>

【讨论】:

  • 这绝对是我想要的,但问题是它是全球性的。我可以把它拿出来,但它仍然试图将 url 包装在标题中(就像那些引用 gMaps API 的那些)。有没有理由这样做,即使它应该只在“身体”中寻找? (将其更改为文档也无济于事)。
  • 我更新了示例,这很好用,不会弄乱头部的网址
  • 作为后续,这是我最终成功使用的内容:function urlwrap( str ) { return '&lt;a href="' + str + '" target="_blank"&gt;' + str + '&lt;/a&gt;'; }; var text= 'data[i].text.replace(/\bhttp[^ ]+/ig, urlwrap)' 并将文本变量写入页面,其中包含从 JSON 响应解析的信息 - [i]。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-11
  • 2017-01-08
  • 2021-10-25
  • 2020-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多