首页 > 解决方案 > 查找元素内的所有@tagnames,然后在其上插入一个链接

问题描述

我有我的html

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

在页面加载时,我想使用循环在类中找到这个@samplename并将其插入到jQueryJavascript的标记中.comment-details.each()<a href="samplelink"></a>

页面加载后我想要这样的东西:

<div class="comment-details">Hello <a href="samplelink">@samplename</a> This is my comment</div>

标签: javascriptjqueryhtml

解决方案


jQuery实现:

$('.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>

在此处输入图像描述


推荐阅读