代码之家  ›  专栏  ›  技术社区  ›  Mark Salvania

在元素中找到所有@tagnames,然后在其上插入链接

  •  1
  • Mark Salvania  · 技术社区  · 7 年前

    <div class="comment-details">Hello @samplename This is my comment</div>
    ...
    ...
    More .comment-details elements
    

    在页面加载时,我想找到这个 里面 .comment-details .each() 循环并插入 <a href="samplelink"></a> 标记 Javascript语言

    <div class="comment-details">Hello <a href="samplelink">@samplename</a> This is my comment</div>
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   95faf8e76605e973    7 年前

    $('.comment-details').each(function(){
        $(this).html($(this).html().replace(/\@.+?\b/g, `<a href=profile/${$(this).html().match(/\@.+?\b/g)[0].replace('@','')}>${$(this).html().match(/\@.+?\b/g)}</a>`));
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="comment-details">Hello @samplename This is my comment</div>
    <div class="comment-details">Hello @JG This is my comment</div>

    enter image description here

        2
  •  1
  •   m0meni Chayim Friedman    7 年前

    [...document.querySelectorAll('.comment-details')]
    .forEach(tag => {
      tag.innerHTML = tag.innerHTML
        .replace(/\s?@(\w+)\s?/g, ' <a href="https://twitter.com/$1">@$1</a> ')
    })
    <div class="comment-details">Wow @m0meni great answer</div>
    <div class="comment-details">@m0meni a little self-congratulatory though</div>

    解释每个步骤: