我有我的html
<div class="comment-details">Hello @samplename This is my comment</div>
...
...
More .comment-details elements
在页面加载时,我想使用.comment-details
循环在.each()
类中找到此 @samplename ,并将其插入 jQuery中的<a href="samplelink"></a>
标签上或 JavaScript
页面加载后我想要这样的东西:
<div class="comment-details">Hello <a href="samplelink">@samplename</a> This is my comment</div>
答案 0 :(得分:2)
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>
答案 1 :(得分:1)
您可以在原始JS中完成
[...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>
解释每个步骤:
querySelectorAll
获取所有评论详细信息divs [...]
是因为In Javascript, what is the best way to convert a NodeList to an array /\s?@(\w+)\s?/g
抓取@之后的所有字符,并且只有在两边都没有空格/即hi @ potoato不匹配的情况下才抓取