javascript - 查找元素内的所有@tagnames,然后在其上插入一个链接
问题描述
我有我的html
<div class="comment-details">Hello @samplename This is my comment</div>
...
...
More .comment-details elements
在页面加载时,我想使用循环在类中找到这个@samplename并将其插入到jQuery或Javascript的标记中.comment-details
.each()
<a href="samplelink"></a>
页面加载后我想要这样的东西:
<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>
推荐阅读
- kdb - 如何提高 ctps 和客户端 procs 之间的发布效率?
- python - Python - 语法错误:扫描字符串文字时 EOL(对于 Google 表格凭据)
- javascript - aframe 全屏模式不显示关闭按钮或自定义按钮
- android - 从 Firestore 中删除数组中的地图数据
- javascript - Postgres 和 Knex.js 中的批量更新,有没有办法准确判断哪些行已更新?
- android - Firebase 测试实验室上传的 APK 未指定主启动器活动
- reactjs - 如何在 reactstrap v.9(bootstrap v.5)中使用模态?
- python - 在 django 迁移中执行 RunPython 时出现“对象没有属性”
- compiler-options - XC16 C 编译器选项 - 使用聚合数据模型
- java - 为 Jenkins 插件导入模块时遇到问题