【问题标题】:replace() or wrap() http://name.tld/request_url?parameter with <a href="this">...</a>?replace() 或 wrap() http://name.tld/request_url?parameter with <a href="this">...</a>?
【发布时间】:2011-04-06 18:33:25
【问题描述】:

有没有更好的方法用&lt;a href&gt;替换/包装某些html元素中的h*tp://name.tld/request_url?parameterh*tps://name.tld/request_url?parameter文本。

这是我的代码:

jQuery('#posts .post').each(function() {
  elem = jQuery(this);
  elem.html(
    elem.text()
    .replace(/(http?:\/\/?\S+)/g, "<a href='$1'>$1</a>")
  );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="posts">
  <div class="post">
    Tweet text 1 http://google.com and other text.
  </div>
  <div class="post">
    Tweet text 2 https://www.google.com and other text.
  </div>
  <div class="post">
    Tweet text 3
  </div>
  <div class="post">
    ...
  </div>
</div>

任何jQuery.wrap() 替代方案也不错。

【问题讨论】:

    标签: javascript jquery regex replace


    【解决方案1】:

    没有比这更好的方法了,不过你可以稍微简化一下,像这样:

    jQuery('#posts .post').each( function () {
      jQuery(this).html(function(i, html) {
        return html.replace(/(http?:\/\/?\S+)/g, "<a href='$1'>$1</a>");
      }); 
    });
    

    仅在您确定帖子不包含 HTML 的情况下使用此方法,否则请使用您拥有的内容。

    jQuery 与 DOM 节点一起工作,而不是节点内的文本,或者更确切地说,因为它只是 JavaScript……但它没有为此提供很多额外的功能。 jQuery,包括 .wrap(),专注于 DOM 操作,而不是文本。

    【讨论】:

    • 你是对的 - wrap() 不适用于纯文本,如果节点内可能有任何其他 HTML 代码,则不应使用 text()。我的问题只是,是否有任何方法可以用更少的代码/努力做到这一点?该代码也可以更早地被操纵......例如服务器端或 AJAX 调用的响应成功函数中。无论如何谢谢你的回答......
    • @gabel - 我从未见过真正便宜的方法,除非你提前在服务器端(我会)这样做。
    猜你喜欢
    • 2022-12-01
    • 2021-12-19
    • 2013-03-02
    • 2011-08-02
    • 2022-12-27
    • 2021-03-05
    • 2022-12-01
    • 1970-01-01
    • 2022-12-01
    相关资源
    最近更新 更多