javascript - 查找元素内的所有@tagnames,然后在其上插入链接

标签 javascript jquery html

我有我的html

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

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

中的标记

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

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

最佳答案

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>

enter image description here

关于javascript - 查找元素内的所有@tagnames,然后在其上插入链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52319421/

相关文章:

javascript - 谁拥有最多的钱 - Codewars 挑战 - JavaScript

javascript - 在不在 span 标记内的 span 文本后添加文本

javascript - 通过 Kinetic.js 文本元素中的字符串索引获取单词/字符屏幕位置

javascript - 前 10 个 jquery

python - 使用 Python 从 HTML 生成目录

html - Angular Material - 黑暗模式改变背景图像

javascript - JScrollPane 不会滚动整个 div? -- JScrollPane 不会随 div 在窗口调整大小时动态移动

javascript - 为什么我们需要在父组件中保存状态

javascript - 如何使用webview在ios objective c safari中打开window.open方法

菜单项的 JavaScript 旋转在单击后卡住